2024-06-17 18:51:02 +00:00
|
|
|
package daemon
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-07-07 18:01:10 +00:00
|
|
|
"crypto/rand"
|
|
|
|
"encoding/hex"
|
2024-07-13 12:34:06 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io/fs"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2024-06-17 18:51:02 +00:00
|
|
|
"time"
|
2024-07-06 13:36:48 +00:00
|
|
|
|
|
|
|
"dev.mediocregopher.com/mediocre-go-lib.git/mlog"
|
2024-06-17 18:51:02 +00:00
|
|
|
)
|
|
|
|
|
2024-07-06 13:36:48 +00:00
|
|
|
// until keeps trying fn until it returns nil, returning true. If the context is
|
|
|
|
// canceled then until returns false.
|
|
|
|
func until(
|
|
|
|
ctx context.Context,
|
|
|
|
logger *mlog.Logger,
|
|
|
|
descr string,
|
|
|
|
fn func(context.Context) error,
|
|
|
|
) bool {
|
2024-06-17 18:51:02 +00:00
|
|
|
for {
|
2024-07-06 13:36:48 +00:00
|
|
|
logger.Info(ctx, descr)
|
|
|
|
err := fn(ctx)
|
|
|
|
if err == nil {
|
|
|
|
return true
|
2024-06-17 18:51:02 +00:00
|
|
|
} else if ctxErr := ctx.Err(); ctxErr != nil {
|
2024-07-06 13:36:48 +00:00
|
|
|
return false
|
2024-06-17 18:51:02 +00:00
|
|
|
}
|
|
|
|
|
2024-07-06 13:36:48 +00:00
|
|
|
logger.Warn(ctx, descr+" failed, retrying in one second", err)
|
2024-06-17 18:51:02 +00:00
|
|
|
time.Sleep(1 * time.Second)
|
|
|
|
}
|
|
|
|
}
|
2024-07-07 18:01:10 +00:00
|
|
|
|
|
|
|
func randStr(l int) string {
|
|
|
|
b := make([]byte, l)
|
|
|
|
if _, err := rand.Read(b); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return hex.EncodeToString(b)
|
|
|
|
}
|
2024-07-13 12:34:06 +00:00
|
|
|
|
|
|
|
// mkDir is like os.Mkdir but it returns better error messages. If the directory
|
|
|
|
// already exists then nil is returned.
|
|
|
|
func mkDir(path string) error {
|
|
|
|
{
|
|
|
|
parentPath := filepath.Dir(path)
|
|
|
|
parentInfo, err := os.Stat(parentPath)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("checking fs node of parent %q: %w", parentPath, err)
|
|
|
|
} else if !parentInfo.IsDir() {
|
|
|
|
return fmt.Errorf("%q is not a directory", parentPath)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
info, err := os.Stat(path)
|
|
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
|
|
// fine
|
|
|
|
} else if err != nil {
|
|
|
|
return fmt.Errorf("checking fs node: %w", err)
|
|
|
|
} else if !info.IsDir() {
|
|
|
|
return fmt.Errorf("exists but is not a directory")
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := os.Mkdir(path, 0700); err != nil {
|
|
|
|
return fmt.Errorf("creating directory: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|