github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/cmd/snaplock/lock.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2017 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 // Package snaplock offers per-snap locking also used by snap-confine. 21 // The corresponding C code is in libsnap-confine-private/locking.c 22 package snaplock 23 24 import ( 25 "fmt" 26 "os" 27 "path/filepath" 28 29 "github.com/snapcore/snapd/dirs" 30 "github.com/snapcore/snapd/osutil" 31 ) 32 33 // lockFileName returns the name of the lock file for the given snap. 34 func lockFileName(snapName string) string { 35 return filepath.Join(dirs.SnapRunLockDir, fmt.Sprintf("%s.lock", snapName)) 36 } 37 38 // OpenLock creates and opens a lock file associated with a particular snap. 39 func OpenLock(snapName string) (*osutil.FileLock, error) { 40 if err := os.MkdirAll(dirs.SnapRunLockDir, 0700); err != nil { 41 return nil, fmt.Errorf("cannot create lock directory: %s", err) 42 } 43 flock, err := osutil.NewFileLock(lockFileName(snapName)) 44 if err != nil { 45 return nil, err 46 } 47 return flock, nil 48 }