Skip to content

Commit 2a2e682

Browse files
fix NewObjectId when running in container (globalsign#33)
1 parent fd13038 commit 2a2e682

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

bson/bson.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ func readRandomUint32() uint32 {
257257
// machineId stores machine id generated once and used in subsequent calls
258258
// to NewObjectId function.
259259
var machineId = readMachineId()
260-
var processId = os.Getpid()
260+
var processId = readProcessId()
261261

262262
// readMachineId generates and returns a machine id.
263263
// If this function fails to get the hostname it will cause a runtime error.
@@ -278,6 +278,23 @@ func readMachineId() []byte {
278278
return id
279279
}
280280

281+
// readProcessId reads process id.
282+
// If it is too small, then probably we are running in docker, and pid will be always constant. In this case lets generate it.
283+
func readProcessId() uint16 {
284+
pid := os.Getpid()
285+
if pid > 10 {
286+
// ok, we are not in docker (I hope so)
287+
return uint16(pid)
288+
}
289+
var buf [2]byte
290+
_, err := io.ReadFull(rand.Reader, buf[:])
291+
if err != nil {
292+
// ough, fallback to pid
293+
return uint16(pid)
294+
}
295+
return uint16(buf[0])<<8 | uint16(buf[1])
296+
}
297+
281298
// NewObjectId returns a new unique ObjectId.
282299
func NewObjectId() ObjectId {
283300
var b [12]byte

0 commit comments

Comments
 (0)