tryCreateLockFile atomically creates the lock file using O_CREATE|O_EXCL and writes the current process's PID and start time into it as JSON. The file is created with 0600 permissions (owner read/write only).
(path string)
| 179 | // and writes the current process's PID and start time into it as JSON. |
| 180 | // The file is created with 0600 permissions (owner read/write only). |
| 181 | func tryCreateLockFile(path string) (retErr error) { |
| 182 | f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) // nolint: gosec |
| 183 | if err != nil { |
| 184 | return err |
| 185 | } |
| 186 | defer func() { |
| 187 | if retErr != nil { |
| 188 | _ = f.Close() |
| 189 | _ = os.Remove(path) |
| 190 | return |
| 191 | } |
| 192 | retErr = f.Close() |
| 193 | }() |
| 194 | |
| 195 | content, err := newSelfLockContent() |
| 196 | if err != nil { |
| 197 | return err |
| 198 | } |
| 199 | |
| 200 | return json.NewEncoder(f).Encode(content) |
| 201 | } |
| 202 | |
| 203 | // newSelfLockContent returns a lockContent describing the current process. |
| 204 | func newSelfLockContent() (lockContent, error) { |