feat: ensure google cloud run compatibility (#3388)

* feat: ensure google cloud run compatibility

* from scratch docker image

* fall back to cloud run container id for sonyflake
This commit is contained in:
Elio Bischof
2022-03-31 10:49:08 +02:00
committed by GitHub
parent 958362e6c9
commit 55af4a18a2
4 changed files with 58 additions and 5 deletions

View File

@@ -2,7 +2,11 @@ package id
import (
"errors"
"fmt"
"hash/fnv"
"io/ioutil"
"net"
"net/http"
"os"
"strconv"
@@ -26,7 +30,7 @@ func (s *sonyflakeGenerator) Next() (string, error) {
var (
SonyFlakeGenerator = Generator(&sonyflakeGenerator{
sonyflake.NewSonyflake(sonyflake.Settings{
MachineID: lower16BitPrivateIP,
MachineID: machineID,
StartTime: time.Date(2019, 4, 29, 0, 0, 0, 0, time.UTC),
}),
})
@@ -68,6 +72,19 @@ func isPrivateIPv4(ip net.IP) bool {
(ip[0] == 10 || ip[0] == 172 && (ip[1] >= 16 && ip[1] < 32) || ip[0] == 192 && ip[1] == 168)
}
func machineID() (uint16, error) {
ip, ipErr := lower16BitPrivateIP()
if ipErr == nil {
return ip, nil
}
cid, cidErr := cloudRunContainerID()
if cidErr != nil {
return 0, fmt.Errorf("neighter found a private ip nor a cloud run container instance id: private ip err: %w, cloud run ip err: %s", ipErr, cidErr.Error())
}
return cid, nil
}
func lower16BitPrivateIP() (uint16, error) {
ip, err := privateIPv4()
if err != nil {
@@ -76,3 +93,36 @@ func lower16BitPrivateIP() (uint16, error) {
return uint16(ip[2])<<8 + uint16(ip[3]), nil
}
func cloudRunContainerID() (uint16, error) {
req, err := http.NewRequest(
http.MethodGet,
"http://metadata.google.internal/computeMetadata/v1/instance/id",
nil,
)
if err != nil {
return 0, err
}
req.Header.Set("Metadata-Flavor", "Google")
resp, err := (&http.Client{}).Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 && resp.StatusCode < 600 {
return 0, fmt.Errorf("cloud metadata returned an unsuccessful status code %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
h := fnv.New32()
if _, err = h.Write(body); err != nil {
return 0, err
}
return uint16(h.Sum32()), nil
}