go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/mmutex/lib/exclusive.go (about)

     1  // Copyright 2017 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package lib
    16  
    17  import (
    18  	"context"
    19  	"os"
    20  
    21  	"github.com/danjacques/gofslock/fslock"
    22  	"github.com/maruel/subcommands"
    23  	"go.chromium.org/luci/common/logging"
    24  )
    25  
    26  // RunExclusive runs the command with the specified context and environment while
    27  // holding an exclusive mmutex lock.
    28  func RunExclusive(ctx context.Context, env subcommands.Env, command func(context.Context) error) error {
    29  	lockFilePath, drainFilePath, err := computeMutexPaths(env)
    30  	if err != nil {
    31  		return err
    32  	}
    33  
    34  	logging.Infof(ctx, "[mmutex][exclusive] LockFilePath: %s, DrainFilePath: %s.", lockFilePath, drainFilePath)
    35  	if len(lockFilePath) == 0 {
    36  		return command(ctx)
    37  	}
    38  
    39  	file, err := os.OpenFile(drainFilePath, os.O_RDONLY|os.O_CREATE, 0666)
    40  	if err != nil {
    41  		return err
    42  	}
    43  	if err = file.Close(); err != nil {
    44  		return err
    45  	}
    46  	// Remove the drain file in case the lock can never be acquired.
    47  	defer RemoveDrainFile(ctx, drainFilePath)
    48  
    49  	blocker := createLockBlocker(ctx)
    50  	return fslock.WithBlocking(lockFilePath, blocker, func() error {
    51  		// Remove the drain file immediately after acquiring the lock in order
    52  		// to decrease the likelihood that a crash occurs, leaving the drain
    53  		// file sitting around indefinitely.
    54  		if err := os.Remove(drainFilePath); err != nil {
    55  			logging.Errorf(ctx, "[mmutex][exclusive] Failed to remove drain file after acquiring the lock: %s", drainFilePath)
    56  			return err
    57  		}
    58  		logging.Infof(ctx, "[mmutex][exclusive] Lock acquired and drain file removed.")
    59  
    60  		return command(ctx)
    61  	})
    62  }
    63  
    64  func RemoveDrainFile(ctx context.Context, drainFilePath string) {
    65  	if err := os.Remove(drainFilePath); err != nil && !os.IsNotExist(err) {
    66  		logging.Errorf(ctx, "[mmutex][exclusive] Failed to remove drain file: %s", err)
    67  	}
    68  }