非HostNetwork模式K8s Pod获取宿主机MAC及Node UID源码查询
Great catch on noticing that the suffix of your Node's UID matches the host's MAC address! This isn't a coincidence—let's break down the logic behind how Kubernetes generates Node UIDs, especially why this correlation exists in older clusters.
Why the UID Suffix Matches the MAC Address
The Node UID in your example is a UUIDv1 (Universally Unique Identifier Version 1). UUIDv1 is structured to include a timestamp and a node identifier, which by default uses the host's MAC address for uniqueness. Here's the breakdown of your Node UID 96557f0f-fea6-11e8-b826-525400a9edd3:
- The last 12 hex characters (
525400a9edd3) correspond exactly to your host's MAC address52:54:00:a9:ed:d3(just remove the colons). This is the "node identifier" segment of the UUIDv1, designed to uniquely identify the machine generating the UUID.
Kubernetes Source Code Logic for Node UID Generation
Let's walk through how this UID gets created in older Kubernetes versions (pre-v1.14, where UUIDv1 was the default):
- Kubelet Node Registration: When a kubelet first starts up on a node, it sends a request to the Kubernetes API Server to create a Node object (if it doesn't already exist).
- API Server UID Generation: The API Server handles the Node creation request. If the incoming Node object doesn't have a UID specified, the API Server generates one.
- In older versions, the API Server used the
github.com/pborman/uuidlibrary'sNewUUID()function, which produces UUIDv1s. - This library's
nodeID()function fetches the host's MAC address (prioritizing non-loopback network interfaces) to use as the node identifier segment of the UUIDv1. - You can find this logic in the API Server's storage layer: specifically in
k8s.io/apiserver/pkg/storage/etcd3/store.gowithin theCreatemethod, where it callsuuid.NewUUID()to generate the UID for new objects.
- In older versions, the API Server used the
Important Caveat for Newer Clusters
Starting with Kubernetes v1.14, the default UID generation switched from UUIDv1 to UUIDv4 (randomly generated UUIDs). This change was made to avoid leaking timestamp and host hardware information via UUIDs. So in newer clusters, you won't see this correlation between Node UIDs and host MAC addresses anymore.
内容的提问来源于stack exchange,提问作者toper

