update-vendor.sh 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #!/usr/bin/env bash
  2. # Copyright 2019 The Kubernetes Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. set -o errexit
  16. set -o nounset
  17. set -o pipefail
  18. KUBE_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
  19. source "${KUBE_ROOT}/hack/lib/init.sh"
  20. # Explicitly opt into go modules, even though we're inside a GOPATH directory
  21. export GO111MODULE=on
  22. # Explicitly clear GOFLAGS, since GOFLAGS=-mod=vendor breaks dependency resolution while rebuilding vendor
  23. export GOFLAGS=
  24. # Ensure sort order doesn't depend on locale
  25. export LANG=C
  26. export LC_ALL=C
  27. # Detect problematic GOPROXY settings that prevent lookup of dependencies
  28. if [[ "${GOPROXY:-}" == "off" ]]; then
  29. kube::log::error "Cannot run hack/update-vendor.sh with \$GOPROXY=off"
  30. exit 1
  31. fi
  32. kube::golang::verify_go_version
  33. kube::util::require-jq
  34. TMP_DIR="${TMP_DIR:-$(mktemp -d /tmp/update-vendor.XXXX)}"
  35. LOG_FILE="${LOG_FILE:-${TMP_DIR}/update-vendor.log}"
  36. kube::log::status "logfile at ${LOG_FILE}"
  37. if [ -z "${BASH_XTRACEFD:-}" ]; then
  38. exec 19> "${LOG_FILE}"
  39. export BASH_XTRACEFD="19"
  40. set -x
  41. fi
  42. # ensure_require_replace_directives_for_all_dependencies:
  43. # - ensures all existing 'require' directives have an associated 'replace' directive pinning a version
  44. # - adds explicit 'require' directives for all transitive dependencies
  45. # - adds explicit 'replace' directives for all require directives (existing 'replace' directives take precedence)
  46. function ensure_require_replace_directives_for_all_dependencies() {
  47. local local_tmp_dir
  48. local_tmp_dir=$(mktemp -d "${TMP_DIR}/pin_replace.XXXX")
  49. # collect 'require' directives that actually specify a version
  50. local require_filter='(.Version != null) and (.Version != "v0.0.0") and (.Version != "v0.0.0-00010101000000-000000000000")'
  51. # collect 'replace' directives that unconditionally pin versions (old=new@version)
  52. local replace_filter='(.Old.Version == null) and (.New.Version != null)'
  53. # Capture local require/replace directives before running any go commands that can modify the go.mod file
  54. local require_json="${local_tmp_dir}/require.json"
  55. local replace_json="${local_tmp_dir}/replace.json"
  56. go mod edit -json | jq -r ".Require // [] | sort | .[] | select(${require_filter})" > "${require_json}"
  57. go mod edit -json | jq -r ".Replace // [] | sort | .[] | select(${replace_filter})" > "${replace_json}"
  58. # 1a. Ensure replace directives have an explicit require directive
  59. cat "${replace_json}" | jq -r '"-require \(.Old.Path)@\(.New.Version)"' | xargs -L 100 go mod edit -fmt
  60. # 1b. Ensure require directives have a corresponding replace directive pinning a version
  61. cat "${require_json}" | jq -r '"-replace \(.Path)=\(.Path)@\(.Version)"' | xargs -L 100 go mod edit -fmt
  62. cat "${replace_json}" | jq -r '"-replace \(.Old.Path)=\(.New.Path)@\(.New.Version)"'| xargs -L 100 go mod edit -fmt
  63. # 2. Propagate root replace/require directives into staging modules, in case we are downgrading, so they don't bump the root required version back up
  64. for repo in $(ls staging/src/k8s.io); do
  65. pushd "staging/src/k8s.io/${repo}" >/dev/null 2>&1
  66. cat "${require_json}" | jq -r '"-require \(.Path)@\(.Version)"' | xargs -L 100 go mod edit -fmt
  67. cat "${require_json}" | jq -r '"-replace \(.Path)=\(.Path)@\(.Version)"' | xargs -L 100 go mod edit -fmt
  68. cat "${replace_json}" | jq -r '"-replace \(.Old.Path)=\(.New.Path)@\(.New.Version)"'| xargs -L 100 go mod edit -fmt
  69. popd >/dev/null 2>&1
  70. done
  71. # 3. Add explicit require directives for indirect dependencies
  72. go list -m -json all | jq -r 'select(.Main != true) | select(.Indirect == true) | "-require \(.Path)@\(.Version)"' | xargs -L 100 go mod edit -fmt
  73. # 4. Add explicit replace directives pinning dependencies that aren't pinned yet
  74. go list -m -json all | jq -r 'select(.Main != true) | select(.Replace == null) | "-replace \(.Path)=\(.Path)@\(.Version)"' | xargs -L 100 go mod edit -fmt
  75. }
  76. function group_replace_directives() {
  77. local local_tmp_dir
  78. local_tmp_dir=$(mktemp -d "${TMP_DIR}/group_replace.XXXX")
  79. local go_mod_replace="${local_tmp_dir}/go.mod.replace.tmp"
  80. local go_mod_noreplace="${local_tmp_dir}/go.mod.noreplace.tmp"
  81. # separate replace and non-replace directives
  82. cat go.mod | awk "
  83. # print lines between 'replace (' ... ')' lines
  84. /^replace [(]/ { inreplace=1; next }
  85. inreplace && /^[)]/ { inreplace=0; next }
  86. inreplace { print > \"${go_mod_replace}\"; next }
  87. # print ungrouped replace directives with the replace directive trimmed
  88. /^replace [^(]/ { sub(/^replace /,\"\"); print > \"${go_mod_replace}\"; next }
  89. # otherwise print to the noreplace file
  90. { print > \"${go_mod_noreplace}\" }
  91. "
  92. cat "${go_mod_noreplace}" > go.mod
  93. echo "replace (" >> go.mod
  94. cat "${go_mod_replace}" >> go.mod
  95. echo ")" >> go.mod
  96. go mod edit -fmt
  97. }
  98. function add_generated_comments() {
  99. local local_tmp_dir
  100. local_tmp_dir=$(mktemp -d "${TMP_DIR}/add_generated_comments.XXXX")
  101. local go_mod_nocomments="${local_tmp_dir}/go.mod.nocomments.tmp"
  102. # drop comments before the module directive
  103. cat go.mod | awk "
  104. BEGIN { dropcomments=1 }
  105. /^module / { dropcomments=0 }
  106. dropcomments && /^\/\// { next }
  107. { print }
  108. " > "${go_mod_nocomments}"
  109. # Add the specified comments
  110. local comments="${1}"
  111. echo "${comments}" > go.mod
  112. echo "" >> go.mod
  113. cat "${go_mod_nocomments}" >> go.mod
  114. # Format
  115. go mod edit -fmt
  116. }
  117. # Phase 1: ensure go.mod files for staging modules and main module
  118. for repo in $(ls staging/src/k8s.io); do
  119. pushd "staging/src/k8s.io/${repo}" >/dev/null 2>&1
  120. if [[ ! -f go.mod ]]; then
  121. kube::log::status "go.mod: initialize ${repo}"
  122. rm -f Godeps/Godeps.json # remove before initializing, staging Godeps are not authoritative
  123. go mod init "k8s.io/${repo}"
  124. go mod edit -fmt
  125. fi
  126. popd >/dev/null 2>&1
  127. done
  128. if [[ ! -f go.mod ]]; then
  129. kube::log::status "go.mod: initialize k8s.io/kubernetes"
  130. go mod init "k8s.io/kubernetes"
  131. rm -f Godeps/Godeps.json # remove after initializing
  132. fi
  133. # Phase 2: ensure staging repo require/replace directives
  134. kube::log::status "go.mod: update staging references"
  135. # Prune
  136. go mod edit -json | jq -r '.Require[]? | select(.Version == "v0.0.0") | "-droprequire \(.Path)"' | xargs -L 100 go mod edit -fmt
  137. go mod edit -json | jq -r '.Replace[]? | select(.New.Path | startswith("./staging/")) | "-dropreplace \(.Old.Path)"' | xargs -L 100 go mod edit -fmt
  138. # Readd
  139. ls staging/src/k8s.io | sort | xargs -n 1 -I {} echo "-require k8s.io/{}@v0.0.0" | xargs -L 100 go mod edit -fmt
  140. ls staging/src/k8s.io | sort | xargs -n 1 -I {} echo "-replace k8s.io/{}=./staging/src/k8s.io/{}" | xargs -L 100 go mod edit -fmt
  141. # Phase 3: capture required (minimum) versions from all modules, and replaced (pinned) versions from the root module
  142. # pin referenced versions
  143. ensure_require_replace_directives_for_all_dependencies
  144. # resolves/expands references in the root go.mod (if needed)
  145. go mod tidy >>"${LOG_FILE}" 2>&1
  146. # pin expanded versions
  147. ensure_require_replace_directives_for_all_dependencies
  148. # group replace directives
  149. group_replace_directives
  150. # Phase 4: copy root go.mod to staging dirs and rewrite
  151. kube::log::status "go.mod: propagate to staging modules"
  152. for repo in $(ls staging/src/k8s.io | sort); do
  153. pushd "staging/src/k8s.io/${repo}" >/dev/null 2>&1
  154. echo "=== propagating to ${repo}" >> "${LOG_FILE}"
  155. # copy root go.mod, changing module name
  156. cat "${KUBE_ROOT}/go.mod" | sed "s#module k8s.io/kubernetes#module k8s.io/${repo}#" > "${KUBE_ROOT}/staging/src/k8s.io/${repo}/go.mod"
  157. # remove `require` directives for staging components (will get re-added as needed by `go list`)
  158. ls "${KUBE_ROOT}/staging/src/k8s.io" | sort | xargs -n 1 -I {} echo "-droprequire k8s.io/{}" | xargs -L 100 go mod edit
  159. # rewrite `replace` directives for staging components to point to peer directories
  160. ls "${KUBE_ROOT}/staging/src/k8s.io" | sort | xargs -n 1 -I {} echo "-replace k8s.io/{}=../{}" | xargs -L 100 go mod edit
  161. popd >/dev/null 2>&1
  162. done
  163. # Phase 5: sort and tidy staging components
  164. kube::log::status "go.mod: sorting staging modules"
  165. # tidy staging repos in reverse dependency order.
  166. # the content of dependencies' go.mod files affects what `go mod tidy` chooses to record in a go.mod file.
  167. ls staging/src/k8s.io | sort | xargs -I {} echo "k8s.io/{}" > "${TMP_DIR}/tidy_unordered.txt"
  168. rm -f "${TMP_DIR}/tidy_deps.txt"
  169. for repo in $(cat "${TMP_DIR}/tidy_unordered.txt"); do
  170. # record existence of the repo to ensure modules with no peer relationships still get included in the order
  171. echo "${repo} ${repo}" >> "${TMP_DIR}/tidy_deps.txt"
  172. pushd "${KUBE_ROOT}/staging/src/${repo}" >/dev/null 2>&1
  173. # save the original go.mod, since go list doesn't just add missing entries, it also removes specific required versions from it
  174. tmp_go_mod="${TMP_DIR}/tidy_${repo/\//_}_go.mod.original"
  175. tmp_go_deps="${TMP_DIR}/tidy_${repo/\//_}_deps.txt"
  176. cp go.mod "${tmp_go_mod}"
  177. echo "=== sorting ${repo}" >> "${LOG_FILE}"
  178. # 'go list' calculates direct imports and updates go.mod so that go list -m lists our module dependencies
  179. echo "=== computing imports for ${repo}" >> "${LOG_FILE}"
  180. go list all >>"${LOG_FILE}" 2>&1
  181. echo "=== computing tools imports for ${repo}" >> "${LOG_FILE}"
  182. go list -tags=tools all >>"${LOG_FILE}" 2>&1
  183. # capture module dependencies
  184. go list -m -f '{{if not .Main}}{{.Path}}{{end}}' all > "${tmp_go_deps}"
  185. # restore the original go.mod file
  186. cp "${tmp_go_mod}" go.mod
  187. # list all module dependencies
  188. for dep in $(join "${TMP_DIR}/tidy_unordered.txt" "${tmp_go_deps}"); do
  189. # record the relationship (put dep first, because we want to sort leaves first)
  190. echo "${dep} ${repo}" >> "${TMP_DIR}/tidy_deps.txt"
  191. # switch the required version to an explicit v0.0.0 (rather than an unknown v0.0.0-00010101000000-000000000000)
  192. go mod edit -require "${dep}@v0.0.0"
  193. done
  194. popd >/dev/null 2>&1
  195. done
  196. kube::log::status "go.mod: tidying"
  197. for repo in $(tsort "${TMP_DIR}/tidy_deps.txt"); do
  198. pushd "${KUBE_ROOT}/staging/src/${repo}" >/dev/null 2>&1
  199. echo "=== tidying ${repo}" >> "${LOG_FILE}"
  200. # prune replace directives that pin to the naturally selected version.
  201. # do this before tidying, since tidy removes unused modules that
  202. # don't provide any relevant packages, which forgets which version of the
  203. # unused transitive dependency we had a require directive for,
  204. # and prevents pruning the matching replace directive after tidying.
  205. go list -m -json all |
  206. jq -r 'select(.Replace != null) |
  207. select(.Path == .Replace.Path) |
  208. select(.Version == .Replace.Version) |
  209. "-dropreplace \(.Replace.Path)"' |
  210. xargs -L 100 go mod edit -fmt
  211. go mod tidy -v >>"${LOG_FILE}" 2>&1
  212. # disallow transitive dependencies on k8s.io/kubernetes
  213. loopback_deps="$(go list all 2>/dev/null | grep k8s.io/kubernetes/ || true)"
  214. if [[ ! -z "${loopback_deps}" ]]; then
  215. kube::log::error "Disallowed ${repo} -> k8s.io/kubernetes dependencies exist via the following imports:
  216. $(go mod why ${loopback_deps})"
  217. exit 1
  218. fi
  219. # prune unused pinned replace directives
  220. comm -23 \
  221. <(go mod edit -json | jq -r '.Replace[] | .Old.Path' | sort) \
  222. <(go list -m -json all | jq -r .Path | sort) |
  223. xargs -L 1 -I {} echo "-dropreplace={}" |
  224. xargs -L 100 go mod edit -fmt
  225. # prune replace directives that pin to the naturally selected version
  226. go list -m -json all |
  227. jq -r 'select(.Replace != null) |
  228. select(.Path == .Replace.Path) |
  229. select(.Version == .Replace.Version) |
  230. "-dropreplace \(.Replace.Path)"' |
  231. xargs -L 100 go mod edit -fmt
  232. popd >/dev/null 2>&1
  233. done
  234. echo "=== tidying root" >> "${LOG_FILE}"
  235. go mod tidy >>"${LOG_FILE}" 2>&1
  236. # Phase 6: add generated comments to go.mod files
  237. kube::log::status "go.mod: adding generated comments"
  238. add_generated_comments "
  239. // This is a generated file. Do not edit directly.
  240. // Run hack/pin-dependency.sh to change pinned dependency versions.
  241. // Run hack/update-vendor.sh to update go.mod files and the vendor directory.
  242. "
  243. for repo in $(ls staging/src/k8s.io | sort); do
  244. pushd "staging/src/k8s.io/${repo}" >/dev/null 2>&1
  245. add_generated_comments "// This is a generated file. Do not edit directly."
  246. popd >/dev/null 2>&1
  247. done
  248. # Phase 6: rebuild vendor directory
  249. kube::log::status "vendor: running 'go mod vendor'"
  250. go mod vendor >>"${LOG_FILE}" 2>&1
  251. # sort recorded packages for a given vendored dependency in modules.txt.
  252. # `go mod vendor` outputs in imported order, which means slight go changes (or different platforms) can result in a differently ordered modules.txt.
  253. # scan | prefix comment lines with the module name | sort field 1 | strip leading text on comment lines
  254. cat vendor/modules.txt | awk '{if($1=="#") print $2 " " $0; else print}' | sort -k1,1 -s | sed 's/.*#/#/' > "${TMP_DIR}/modules.txt.tmp"
  255. mv "${TMP_DIR}/modules.txt.tmp" vendor/modules.txt
  256. # create a symlink in vendor directory pointing to the staging components.
  257. # This lets other packages and tools use the local staging components as if they were vendored.
  258. for repo in $(ls staging/src/k8s.io); do
  259. rm -fr "${KUBE_ROOT}/vendor/k8s.io/${repo}"
  260. ln -s "../../staging/src/k8s.io/${repo}" "${KUBE_ROOT}/vendor/k8s.io/${repo}"
  261. done
  262. kube::log::status "vendor: updating BUILD files"
  263. # Assume that anything imported through vendor doesn't need Bazel to build.
  264. # Prune out any Bazel build files, since these can break the build due to
  265. # missing dependencies that aren't included by go mod vendor.
  266. find vendor/ -type f \( -name BUILD -o -name BUILD.bazel -o -name WORKSPACE \) -exec rm -f {} \;
  267. hack/update-bazel.sh >>"${LOG_FILE}" 2>&1
  268. kube::log::status "vendor: updating LICENSES file"
  269. hack/update-vendor-licenses.sh >>"${LOG_FILE}" 2>&1
  270. kube::log::status "vendor: creating OWNERS file"
  271. rm -f "Godeps/OWNERS" "vendor/OWNERS"
  272. cat <<__EOF__ > "Godeps/OWNERS"
  273. # See the OWNERS docs at https://go.k8s.io/owners
  274. approvers:
  275. - dep-approvers
  276. __EOF__
  277. cp "Godeps/OWNERS" "vendor/OWNERS"