go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/luciexe/host/cleanup.go (about)

     1  // Copyright 2019 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 host
    16  
    17  import (
    18  	"context"
    19  	"os"
    20  
    21  	"go.chromium.org/luci/common/errors"
    22  	"go.chromium.org/luci/common/logging"
    23  	"go.chromium.org/luci/common/system/environ"
    24  )
    25  
    26  type cleanupFn func() error
    27  type cleanupItem struct {
    28  	name string
    29  	cb   cleanupFn
    30  }
    31  type cleanupSlice []cleanupItem
    32  
    33  func (c cleanupSlice) run(ctx context.Context) {
    34  	merr := errors.NewLazyMultiError(len(c))
    35  	for i := len(c) - 1; i >= 0; i-- {
    36  		itm := c[i]
    37  		logging.Infof(ctx, "running cleanup %q", itm.name)
    38  		err := itm.cb()
    39  		if merr.Assign(i, err) {
    40  			logging.WithError(err).Errorf(ctx, "cleanup %q failed", itm.name)
    41  		} else {
    42  			logging.Infof(ctx, "cleanup %q succeeded", itm.name)
    43  		}
    44  	}
    45  	if err := merr.Get(); err != nil {
    46  		panic(err)
    47  	}
    48  }
    49  
    50  func (c *cleanupSlice) concat(cleanup cleanupSlice, err error) error {
    51  	*c = append(*c, cleanup...)
    52  	return err
    53  }
    54  
    55  func (c *cleanupSlice) add(name string, cb cleanupFn) {
    56  	*c = append(*c, cleanupItem{name, cb})
    57  }
    58  
    59  func restoreEnv() cleanupFn {
    60  	origEnv := environ.System()
    61  	return func() error {
    62  		os.Clearenv()
    63  		return errors.Annotate(origEnv.Iter(os.Setenv), "restoring original env").Err()
    64  	}
    65  }