-
Notifications
You must be signed in to change notification settings - Fork 562
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
Meulengracht
wants to merge
6
commits into
snapcore:master
Choose a base branch
from
Meulengracht:feature/refresh-user-services-support
base: master
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6672876
wrappers: add enable+disabledservices for user services and use those…
Meulengracht fbcf397
usersession/client: support -1 as a specifier to affect all users
Meulengracht 7a3d4e1
o/snapstate: support user-services when refreshing snaps
Meulengracht ccc770c
o/servicestate: add missing user-service tracking for hooks
Meulengracht abe095c
many: cleanup, revert the -1 support in services list for client
Meulengracht f1e8be8
o/snapstate: fix a wrong comment
Meulengracht File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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() | ||
} 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{} | ||
|
@@ -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 | ||
|
@@ -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: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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).