Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

o/snapstate: support user-services when refreshing snaps #13905

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
51 changes: 51 additions & 0 deletions client/clientutil/session.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
* Copyright (C) 2024 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/

package clientutil

import (
"path/filepath"
"strconv"

"github.com/snapcore/snapd/dirs"
)

// AvailableUserSessions returns a list of available user-session targets for
// snapd, by probing the available snapd-session-agent sockets in the
// XDG runtime directory.
func AvailableUserSessions() ([]int, error) {
sockets, err := filepath.Glob(filepath.Join(dirs.XdgRuntimeDirGlob, "snapd-session-agent.socket"))
if err != nil {
return nil, err
}

var uids []int
for _, sock := range sockets {
uidStr := filepath.Base(filepath.Dir(sock))
uid, err := strconv.Atoi(uidStr)
if err != nil {
// Ignore directories that do not
// appear to be valid XDG runtime dirs
// (i.e. /run/user/NNNN).
continue
}
uids = append(uids, uid)
}
return uids, nil
}
76 changes: 76 additions & 0 deletions client/clientutil/session_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
* Copyright (C) 2024 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/

package clientutil_test

import (
"os"
"path"
"sort"

"github.com/snapcore/snapd/client/clientutil"
"github.com/snapcore/snapd/dirs"
. "gopkg.in/check.v1"
)

type sessionSuite struct{}

var _ = Suite(&sessionSuite{})

func (s *sessionSuite) SetUpTest(c *C) {
dirs.SetRootDir(c.MkDir())
}

func (s *sessionSuite) TestAvailableUserSessionsHappy(c *C) {
// fake two sockets, one for 0 and one for 1000
err := os.MkdirAll(path.Join(dirs.XdgRuntimeDirBase, "0", "snapd-session-agent.socket"), 0700)
c.Assert(err, IsNil)
err = os.MkdirAll(path.Join(dirs.XdgRuntimeDirBase, "1000", "snapd-session-agent.socket"), 0700)
c.Assert(err, IsNil)
err = os.MkdirAll(path.Join(dirs.XdgRuntimeDirBase, "1337", "snapd-session-agent.socket"), 0700)
c.Assert(err, IsNil)

res, err := clientutil.AvailableUserSessions()
c.Assert(err, IsNil)
c.Check(res, HasLen, 3)
sort.Ints(res)
c.Check(res, DeepEquals, []int{
0,
1000,
1337,
})
}

func (s *sessionSuite) TestAvailableUserSessionsIgnoresBadUids(c *C) {
// fake two sockets, one for 0 and one for 1000
err := os.MkdirAll(path.Join(dirs.XdgRuntimeDirBase, "hello", "snapd-session-agent.socket"), 0700)
c.Assert(err, IsNil)
err = os.MkdirAll(path.Join(dirs.XdgRuntimeDirBase, "*34i8932", "snapd-session-agent.socket"), 0700)
c.Assert(err, IsNil)
err = os.MkdirAll(path.Join(dirs.XdgRuntimeDirBase, "3", "snapd-session-agent.socket"), 0700)
c.Assert(err, IsNil)

res, err := clientutil.AvailableUserSessions()
c.Assert(err, IsNil)
c.Check(res, HasLen, 1)
sort.Ints(res)
c.Check(res, DeepEquals, []int{
3,
})
}
8 changes: 8 additions & 0 deletions overlord/servicestate/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
package servicestate

import (
"os/user"

tomb "gopkg.in/tomb.v2"

"github.com/snapcore/snapd/overlord/state"
Expand Down Expand Up @@ -76,3 +78,9 @@ func MockResourcesCheckFeatureRequirements(f func(*quota.Resources) error) (rest
resourcesCheckFeatureRequirements = f
return r
}

func MockUserLookup(f func(string) (*user.User, error)) (restore func()) {
r := testutil.Backup(&userLookup)
userLookup = f
return r
}
212 changes: 195 additions & 17 deletions overlord/servicestate/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,70 @@ package servicestate

import (
"fmt"
"os/user"
"sort"
"strconv"

"github.com/snapcore/snapd/client/clientutil"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/wrappers"
)

// updateSnapstateServices uses ServicesEnabledByHooks and ServicesDisabledByHooks in
// snapstate and the provided enabled or disabled list to update the state of services in snapstate.
// It is meant for doServiceControl to help track enabling and disabling of services.
func updateSnapstateServices(snapst *snapstate.SnapState, enable, disable []*snap.AppInfo) (bool, error) {
if len(enable) > 0 && len(disable) > 0 {
// We do one op at a time for given service-control task; we could in
// theory support both at the same time here, but service-control
// ops are run sequentially so we always either enable or disable at
// any given time. Not having to worry about that simplifies the
// problem of ordering of enable vs disable.
return false, fmt.Errorf("internal error: cannot handle enabled and disabled services at the same time")
var userLookup = user.Lookup

// usernamesToUids converts a list of usernames, to a list of uids by
// looking up the usernames.
func usernamesToUids(usernames []string) ([]int, error) {
uids := make([]int, 0, len(usernames))
for _, username := range usernames {
usr, err := userLookup(username)
if err != nil {
return nil, err
}
uid, err := strconv.Atoi(usr.Uid)
if err != nil {
return nil, err
}
uids = append(uids, uid)
}
return uids, nil
}

func affectedUids(users []string) (map[int]bool, error) {
var uids []int
var err error
if len(users) == 0 {
uids, err = clientutil.AvailableUserSessions()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is inherently racy. What would be the right thing to do for users who do not have an active session when this code runs? Perhaps the function could use a doc comment clearly indicating that it lists users who currently have an active session (with an agent running in it).

} else {
uids, err = usernamesToUids(users)
}
if err != nil {
return nil, err
}

uidsAffected := make(map[int]bool, len(users))
for _, uid := range uids {
uidsAffected[uid] = true
}
return uidsAffected, nil
}

func splitServicesIntoSystemAndUser(apps []*snap.AppInfo) (sys, usr []*snap.AppInfo) {
for _, app := range apps {
if !app.IsService() {
continue
}
if app.DaemonScope == snap.SystemDaemon {
sys = append(sys, app)
} else {
usr = append(usr, app)
}
}
return sys, usr
}

func updateSnapstateSystemServices(snapst *snapstate.SnapState, apps []*snap.AppInfo, enable bool) bool {
// populate helper lookups of already enabled/disabled services from
// snapst.
alreadyEnabled := map[string]bool{}
Expand Down Expand Up @@ -69,15 +114,14 @@ func updateSnapstateServices(snapst *snapstate.SnapState, enable, disable []*sna
// we are not disabling and enabling the services at the same time as
// checked in the function entry, only one path is possible
fromState, toState := alreadyDisabled, alreadyEnabled
which := enable
if len(disable) > 0 {
if !enable {
fromState, toState = alreadyEnabled, alreadyDisabled
which = disable
}
if changed := toggleServices(which, fromState, toState); !changed {
if changed := toggleServices(apps, fromState, toState); !changed {
// nothing changed
return false, nil
return false
}

// reset and recreate the state
snapst.ServicesEnabledByHooks = nil
snapst.ServicesDisabledByHooks = nil
Expand All @@ -95,5 +139,139 @@ func updateSnapstateServices(snapst *snapstate.SnapState, enable, disable []*sna
}
sort.Strings(snapst.ServicesDisabledByHooks)
}
return true, nil
return true
}

func updateSnapstateUserServices(snapst *snapstate.SnapState, apps []*snap.AppInfo, enable bool, uids map[int]bool) bool {
// populate helper lookups of already enabled/disabled services from
// snapst.
alreadyEnabled := make(map[int]map[string]bool)
alreadyDisabled := make(map[int]map[string]bool)
for uid, names := range snapst.UserServicesEnabledByHooks {
alreadyEnabled[uid] = make(map[string]bool)
for _, name := range names {
alreadyEnabled[uid][name] = true
}
}
for uid, names := range snapst.UserServicesDisabledByHooks {
alreadyDisabled[uid] = make(map[string]bool)
for _, name := range names {
alreadyDisabled[uid][name] = true
}
}

toggleServices := func(services []*snap.AppInfo, fromState map[int]map[string]bool, toState map[int]map[string]bool) (changed bool) {
// we are affecting specific users, so migrate given
// services from one map to another, if they do
// not exist in the target map
for _, service := range services {
for uid := range toState {
// otherwise migrate only if the user is a match
if !uids[uid] {
continue
}

if !toState[uid][service.Name] {
toState[uid][service.Name] = true
if fromState[uid][service.Name] {
delete(fromState[uid], service.Name)
}
changed = true
}
}
}
return changed
}

// we are not disabling and enabling the services at the same time as
// checked in the function entry, only one path is possible
fromState, toState := alreadyDisabled, alreadyEnabled
if !enable {
fromState, toState = alreadyEnabled, alreadyDisabled
}

// ensure uids are in target
for uid := range uids {
if toState[uid] == nil {
toState[uid] = make(map[string]bool)
}
}

if changed := toggleServices(apps, fromState, toState); !changed {
// nothing changed
return false
}

convertStateMap := func(svcState map[int]map[string]bool) map[int][]string {
result := make(map[int][]string, len(svcState))
for uid, svcs := range svcState {
if len(svcs) == 0 {
continue
}

l := make([]string, 0, len(svcs))
for srv := range svcs {
l = append(l, srv)
}
sort.Strings(l)
result[uid] = l
}
return result
}

// reset and recreate the state
snapst.UserServicesEnabledByHooks = nil
snapst.UserServicesDisabledByHooks = nil
if len(alreadyEnabled) != 0 {
snapst.UserServicesEnabledByHooks = convertStateMap(alreadyEnabled)
}
if len(alreadyDisabled) != 0 {
snapst.UserServicesDisabledByHooks = convertStateMap(alreadyDisabled)
}
return true
}

// updateSnapstateServices uses {User,}ServicesEnabledByHooks and {User,}ServicesDisabledByHooks in
// snapstate and the provided enabled or disabled list to update the state of services in snapstate.
// It is meant for doServiceControl to help track enabling and disabling of services.
func updateSnapstateServices(snapst *snapstate.SnapState, enable, disable []*snap.AppInfo, scopeOpts wrappers.ScopeOptions) (bool, error) {
if len(enable) > 0 && len(disable) > 0 {
// We do one op at a time for given service-control task; we could in
// theory support both at the same time here, but service-control
// ops are run sequentially so we always either enable or disable at
// any given time. Not having to worry about that simplifies the
// problem of ordering of enable vs disable.
return false, fmt.Errorf("internal error: cannot handle enabled and disabled services at the same time")
}

// Split into system and user services, and deal with them there
var sys, usr []*snap.AppInfo
if len(enable) > 0 {
sys, usr = splitServicesIntoSystemAndUser(enable)
} else {
sys, usr = splitServicesIntoSystemAndUser(disable)
}

isEnable := len(enable) > 0
switch scopeOpts.Scope {
case wrappers.ServiceScopeAll:
// Retrieve the uids affected
affectedUids, err := affectedUids(scopeOpts.Users)
if err != nil {
return false, err
}
sysChanged := updateSnapstateSystemServices(snapst, sys, isEnable)
usrChanged := updateSnapstateUserServices(snapst, usr, isEnable, affectedUids)
return sysChanged || usrChanged, nil
case wrappers.ServiceScopeSystem:
return updateSnapstateSystemServices(snapst, sys, isEnable), nil
case wrappers.ServiceScopeUser:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this could use a comment that this code path is unlikely to be hit by a hook during refresh

// Retrieve the uids affected
affectedUids, err := affectedUids(scopeOpts.Users)
if err != nil {
return false, err
}
return updateSnapstateUserServices(snapst, sys, isEnable, affectedUids), nil
}
return false, nil
}