mirror of
https://github.com/sony/sonyflake.git
synced 2025-12-23 05:05:14 +00:00
* Add v2 * Introduce staticcheck * Introduce golangci-lint * Add error checks * Add error checks * Lint v2 code * Improve CI trigger * Use io.ReadAll * Use int64 * Remove NewSonyflake * Fix errors * v2: Change MachineID, sequence, and AmazonEC2MachineID to int; update all usage and tests for type consistency * docs: update Settings struct in README to use int for MachineID and CheckMachineID (v2) * docs(v2): clarify Settings, StartTime, MachineID, and CheckMachineID comments and update README links and explanations * docs(v2/mock): improve comments and docstrings for mock implementations * docs(types): unify and clarify package and type docstrings for types.go in v1 and v2 * test(v2): refactor and modernize tests, improve error assertions, and update mocks for v2 * test(v2): normalize whitespace in pseudoSleep calls for consistency * feat(v2): add configurable TimeUnit and refactor time handling for So… (#67) * feat(v2): add configurable TimeUnit and refactor time handling for Sonyflake v2 * test(v2): add ToTime tests, clarify TimeUnit behavior, and update docs for v2 * gofmt
65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
// Package awsutil provides utility functions for using Sonyflake on AWS.
|
|
package awsutil
|
|
|
|
import (
|
|
"errors"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"os/exec"
|
|
"regexp"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
func amazonEC2PrivateIPv4() (net.IP, error) {
|
|
res, err := http.Get("http://169.254.169.254/latest/meta-data/local-ipv4")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
body, err := io.ReadAll(res.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
ip := net.ParseIP(string(body))
|
|
if ip == nil {
|
|
return nil, errors.New("invalid ip address")
|
|
}
|
|
return ip.To4(), nil
|
|
}
|
|
|
|
// AmazonEC2MachineID retrieves the private IP address of the Amazon EC2 instance
|
|
// and returns its lower 16 bits.
|
|
// It works correctly on Docker as well.
|
|
func AmazonEC2MachineID() (int, error) {
|
|
ip, err := amazonEC2PrivateIPv4()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return int(ip[2])<<8 + int(ip[3]), nil
|
|
}
|
|
|
|
// TimeDifference returns the time difference between the localhost and the given NTP server.
|
|
func TimeDifference(server string) (time.Duration, error) {
|
|
output, err := exec.Command("/usr/sbin/ntpdate", "-q", server).CombinedOutput()
|
|
if err != nil {
|
|
return time.Duration(0), err
|
|
}
|
|
|
|
re, _ := regexp.Compile("offset (.*) sec")
|
|
submatched := re.FindSubmatch(output)
|
|
if len(submatched) != 2 {
|
|
return time.Duration(0), errors.New("invalid ntpdate output")
|
|
}
|
|
|
|
f, err := strconv.ParseFloat(string(submatched[1]), 64)
|
|
if err != nil {
|
|
return time.Duration(0), err
|
|
}
|
|
return time.Duration(f*1000) * time.Millisecond, nil
|
|
}
|