configure-helper.sh 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070
  1. #!/usr/bin/env bash
  2. # Copyright 2016 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. # This script is for configuring kubernetes master and node instances. It is
  16. # uploaded in the manifests tar ball.
  17. # TODO: this script duplicates templating logic from cluster/saltbase/salt
  18. # using sed. It should use an actual template parser on the manifest
  19. # files.
  20. set -o errexit
  21. set -o nounset
  22. set -o pipefail
  23. function setup-os-params {
  24. # Reset core_pattern. On GCI, the default core_pattern pipes the core dumps to
  25. # /sbin/crash_reporter which is more restrictive in saving crash dumps. So for
  26. # now, set a generic core_pattern that users can work with.
  27. echo "core.%e.%p.%t" > /proc/sys/kernel/core_pattern
  28. }
  29. # secure_random generates a secure random string of bytes. This function accepts
  30. # a number of secure bytes desired and returns a base64 encoded string with at
  31. # least the requested entropy. Rather than directly reading from /dev/urandom,
  32. # we use uuidgen which calls getrandom(2). getrandom(2) verifies that the
  33. # entropy pool has been initialized sufficiently for the desired operation
  34. # before reading from /dev/urandom.
  35. #
  36. # ARGS:
  37. # #1: number of secure bytes to generate. We round up to the nearest factor of 32.
  38. function secure_random {
  39. local infobytes="${1}"
  40. if ((infobytes <= 0)); then
  41. echo "Invalid argument to secure_random: infobytes='${infobytes}'" 1>&2
  42. return 1
  43. fi
  44. local out=""
  45. for (( i = 0; i < "${infobytes}"; i += 32 )); do
  46. # uuids have 122 random bits, sha256 sums have 256 bits, so concatenate
  47. # three uuids and take their sum. The sum is encoded in ASCII hex, hence the
  48. # 64 character cut.
  49. out+="$(
  50. (
  51. uuidgen --random;
  52. uuidgen --random;
  53. uuidgen --random;
  54. ) | sha256sum \
  55. | head -c 64
  56. )";
  57. done
  58. # Finally, convert the ASCII hex to base64 to increase the density.
  59. echo -n "${out}" | xxd -r -p | base64 -w 0
  60. }
  61. function config-ip-firewall {
  62. echo "Configuring IP firewall rules"
  63. # Do not consider loopback addresses as martian source or destination while
  64. # routing. This enables the use of 127/8 for local routing purposes.
  65. sysctl -w net.ipv4.conf.all.route_localnet=1
  66. # The GCI image has host firewall which drop most inbound/forwarded packets.
  67. # We need to add rules to accept all TCP/UDP/ICMP/SCTP packets.
  68. if iptables -w -L INPUT | grep "Chain INPUT (policy DROP)" > /dev/null; then
  69. echo "Add rules to accept all inbound TCP/UDP/ICMP packets"
  70. iptables -A INPUT -w -p TCP -j ACCEPT
  71. iptables -A INPUT -w -p UDP -j ACCEPT
  72. iptables -A INPUT -w -p ICMP -j ACCEPT
  73. iptables -A INPUT -w -p SCTP -j ACCEPT
  74. fi
  75. if iptables -w -L FORWARD | grep "Chain FORWARD (policy DROP)" > /dev/null; then
  76. echo "Add rules to accept all forwarded TCP/UDP/ICMP/SCTP packets"
  77. iptables -A FORWARD -w -p TCP -j ACCEPT
  78. iptables -A FORWARD -w -p UDP -j ACCEPT
  79. iptables -A FORWARD -w -p ICMP -j ACCEPT
  80. iptables -A FORWARD -w -p SCTP -j ACCEPT
  81. fi
  82. # Flush iptables nat table
  83. iptables -w -t nat -F || true
  84. if [[ "${NON_MASQUERADE_CIDR:-}" == "0.0.0.0/0" ]]; then
  85. echo "Add rules for ip masquerade"
  86. iptables -w -t nat -N IP-MASQ
  87. iptables -w -t nat -A POSTROUTING -m comment --comment "ip-masq: ensure nat POSTROUTING directs all non-LOCAL destination traffic to our custom IP-MASQ chain" -m addrtype ! --dst-type LOCAL -j IP-MASQ
  88. iptables -w -t nat -A IP-MASQ -d 169.254.0.0/16 -m comment --comment "ip-masq: local traffic is not subject to MASQUERADE" -j RETURN
  89. iptables -w -t nat -A IP-MASQ -d 10.0.0.0/8 -m comment --comment "ip-masq: RFC 1918 reserved range is not subject to MASQUERADE" -j RETURN
  90. iptables -w -t nat -A IP-MASQ -d 172.16.0.0/12 -m comment --comment "ip-masq: RFC 1918 reserved range is not subject to MASQUERADE" -j RETURN
  91. iptables -w -t nat -A IP-MASQ -d 192.168.0.0/16 -m comment --comment "ip-masq: RFC 1918 reserved range is not subject to MASQUERADE" -j RETURN
  92. iptables -w -t nat -A IP-MASQ -d 240.0.0.0/4 -m comment --comment "ip-masq: RFC 5735 reserved range is not subject to MASQUERADE" -j RETURN
  93. iptables -w -t nat -A IP-MASQ -d 192.0.2.0/24 -m comment --comment "ip-masq: RFC 5737 reserved range is not subject to MASQUERADE" -j RETURN
  94. iptables -w -t nat -A IP-MASQ -d 198.51.100.0/24 -m comment --comment "ip-masq: RFC 5737 reserved range is not subject to MASQUERADE" -j RETURN
  95. iptables -w -t nat -A IP-MASQ -d 203.0.113.0/24 -m comment --comment "ip-masq: RFC 5737 reserved range is not subject to MASQUERADE" -j RETURN
  96. iptables -w -t nat -A IP-MASQ -d 100.64.0.0/10 -m comment --comment "ip-masq: RFC 6598 reserved range is not subject to MASQUERADE" -j RETURN
  97. iptables -w -t nat -A IP-MASQ -d 198.18.0.0/15 -m comment --comment "ip-masq: RFC 6815 reserved range is not subject to MASQUERADE" -j RETURN
  98. iptables -w -t nat -A IP-MASQ -d 192.0.0.0/24 -m comment --comment "ip-masq: RFC 6890 reserved range is not subject to MASQUERADE" -j RETURN
  99. iptables -w -t nat -A IP-MASQ -d 192.88.99.0/24 -m comment --comment "ip-masq: RFC 7526 reserved range is not subject to MASQUERADE" -j RETURN
  100. iptables -w -t nat -A IP-MASQ -m comment --comment "ip-masq: outbound traffic is subject to MASQUERADE (must be last in chain)" -j MASQUERADE
  101. fi
  102. # If METADATA_CONCEALMENT_NO_FIREWALL is set, don't create a firewall on this
  103. # node because we don't expect the daemonset to run on this node.
  104. if [[ "${ENABLE_METADATA_CONCEALMENT:-}" == "true" ]] && [[ ! "${METADATA_CONCEALMENT_NO_FIREWALL:-}" == "true" ]]; then
  105. echo "Add rule for metadata concealment"
  106. iptables -w -t nat -I PREROUTING -p tcp -d 169.254.169.254 --dport 80 -m comment --comment "metadata-concealment: bridge traffic to metadata server goes to metadata proxy" -j DNAT --to-destination 127.0.0.1:988
  107. fi
  108. }
  109. function create-dirs {
  110. echo "Creating required directories"
  111. mkdir -p /var/lib/kubelet
  112. mkdir -p /etc/kubernetes/manifests
  113. if [[ "${KUBERNETES_MASTER:-}" == "false" ]]; then
  114. mkdir -p /var/lib/kube-proxy
  115. fi
  116. }
  117. # Gets the total number of $(1) and $(2) type disks specified
  118. # by the user in ${NODE_LOCAL_SSDS_EXT}
  119. function get-local-disk-num() {
  120. local interface="${1}"
  121. local format="${2}"
  122. localdisknum=0
  123. if [[ ! -z "${NODE_LOCAL_SSDS_EXT:-}" ]]; then
  124. IFS=";" read -r -a ssdgroups <<< "${NODE_LOCAL_SSDS_EXT:-}"
  125. for ssdgroup in "${ssdgroups[@]}"; do
  126. IFS="," read -r -a ssdopts <<< "${ssdgroup}"
  127. local opnum="${ssdopts[0]}"
  128. local opinterface="${ssdopts[1]}"
  129. local opformat="${ssdopts[2]}"
  130. if [[ "${opformat,,}" == "${format,,}" && "${opinterface,,}" == "${interface,,}" ]]; then
  131. localdisknum=$((localdisknum+opnum))
  132. fi
  133. done
  134. fi
  135. }
  136. # Creates a symlink for a ($1) so that it may be used as block storage
  137. function safe-block-symlink(){
  138. local device="${1}"
  139. local symdir="${2}"
  140. mkdir -p "${symdir}"
  141. get-or-generate-uuid "${device}"
  142. local myuuid="${retuuid}"
  143. local sym="${symdir}/local-ssd-${myuuid}"
  144. # Do not "mkdir -p ${sym}" as that will cause unintended symlink behavior
  145. ln -s "${device}" "${sym}"
  146. echo "Created a symlink for SSD $ssd at ${sym}"
  147. chmod a+w "${sym}"
  148. }
  149. # Gets a pregenerated UUID from ${ssdmap} if it exists, otherwise generates a new
  150. # UUID and places it inside ${ssdmap}
  151. function get-or-generate-uuid(){
  152. local device="${1}"
  153. local ssdmap="/home/kubernetes/localssdmap.txt"
  154. echo "Generating or getting UUID from ${ssdmap}"
  155. if [[ ! -e "${ssdmap}" ]]; then
  156. touch "${ssdmap}"
  157. chmod +w "${ssdmap}"
  158. fi
  159. # each line of the ssdmap looks like "${device} persistent-uuid"
  160. if [[ ! -z $(grep ${device} ${ssdmap}) ]]; then
  161. #create symlink based on saved uuid
  162. local myuuid=$(grep ${device} ${ssdmap} | cut -d ' ' -f 2)
  163. else
  164. # generate new uuid and add it to the map
  165. local myuuid=$(uuidgen)
  166. if [[ ! ${?} -eq 0 ]]; then
  167. echo "Failed to generate valid UUID with uuidgen" >&2
  168. exit 2
  169. fi
  170. echo "${device} ${myuuid}" >> "${ssdmap}"
  171. fi
  172. if [[ -z "${myuuid}" ]]; then
  173. echo "Failed to get a uuid for device ${device} when symlinking." >&2
  174. exit 2
  175. fi
  176. retuuid="${myuuid}"
  177. }
  178. #Formats the given device ($1) if needed and mounts it at given mount point
  179. # ($2).
  180. function safe-format-and-mount() {
  181. local device="${1}"
  182. local mountpoint="${2}"
  183. # Format only if the disk is not already formatted.
  184. if ! tune2fs -l "${device}" ; then
  185. echo "Formatting '${device}'"
  186. mkfs.ext4 -F "${device}"
  187. fi
  188. mkdir -p "${mountpoint}"
  189. echo "Mounting '${device}' at '${mountpoint}'"
  190. mount -o discard,defaults "${device}" "${mountpoint}"
  191. chmod a+w "${mountpoint}"
  192. }
  193. # Gets a devices UUID and bind mounts the device to mount location in
  194. # /mnt/disks/by-id/
  195. function unique-uuid-bind-mount(){
  196. local mountpoint="${1}"
  197. local actual_device="${2}"
  198. # Trigger udev refresh so that newly formatted devices are propagated in by-uuid
  199. udevadm control --reload-rules
  200. udevadm trigger
  201. udevadm settle
  202. # grep the exact match of actual device, prevents substring matching
  203. local myuuid=$(ls -l /dev/disk/by-uuid/ | grep "/${actual_device}$" | tr -s ' ' | cut -d ' ' -f 9)
  204. # myuuid should be the uuid of the device as found in /dev/disk/by-uuid/
  205. if [[ -z "${myuuid}" ]]; then
  206. echo "Failed to get a uuid for device ${actual_device} when mounting." >&2
  207. exit 2
  208. fi
  209. # bindpoint should be the full path of the to-be-bound device
  210. local bindpoint="${UUID_MNT_PREFIX}-${interface}-fs/local-ssd-${myuuid}"
  211. safe-bind-mount "${mountpoint}" "${bindpoint}"
  212. }
  213. # Bind mounts device at mountpoint to bindpoint
  214. function safe-bind-mount(){
  215. local mountpoint="${1}"
  216. local bindpoint="${2}"
  217. # Mount device to the mountpoint
  218. mkdir -p "${bindpoint}"
  219. echo "Binding '${mountpoint}' at '${bindpoint}'"
  220. mount --bind "${mountpoint}" "${bindpoint}"
  221. chmod a+w "${bindpoint}"
  222. }
  223. # Mounts, bindmounts, or symlinks depending on the interface and format
  224. # of the incoming device
  225. function mount-ext(){
  226. local ssd="${1}"
  227. local devicenum="${2}"
  228. local interface="${3}"
  229. local format="${4}"
  230. if [[ -z "${devicenum}" ]]; then
  231. echo "Failed to get the local disk number for device ${ssd}" >&2
  232. exit 2
  233. fi
  234. # TODO: Handle partitioned disks. Right now this code just ignores partitions
  235. if [[ "${format}" == "fs" ]]; then
  236. if [[ "${interface}" == "scsi" ]]; then
  237. local actual_device=$(readlink -f "${ssd}" | cut -d '/' -f 3)
  238. # Error checking
  239. if [[ "${actual_device}" != sd* ]]; then
  240. echo "'actual_device' is not of the correct format. It must be the kernel name of the device, got ${actual_device} instead" >&2
  241. exit 1
  242. fi
  243. local mountpoint="/mnt/disks/ssd${devicenum}"
  244. else
  245. # This path is required because the existing Google images do not
  246. # expose NVMe devices in /dev/disk/by-id so we are using the /dev/nvme instead
  247. local actual_device=$(echo ${ssd} | cut -d '/' -f 3)
  248. # Error checking
  249. if [[ "${actual_device}" != nvme* ]]; then
  250. echo "'actual_device' is not of the correct format. It must be the kernel name of the device, got ${actual_device} instead" >&2
  251. exit 1
  252. fi
  253. local mountpoint="/mnt/disks/ssd-nvme${devicenum}"
  254. fi
  255. safe-format-and-mount "${ssd}" "${mountpoint}"
  256. # We only do the bindmount if users are using the new local ssd request method
  257. # see https://github.com/kubernetes/kubernetes/pull/53466#discussion_r146431894
  258. if [[ ! -z "${NODE_LOCAL_SSDS_EXT:-}" ]]; then
  259. unique-uuid-bind-mount "${mountpoint}" "${actual_device}"
  260. fi
  261. elif [[ "${format}" == "block" ]]; then
  262. local symdir="${UUID_BLOCK_PREFIX}-${interface}-block"
  263. safe-block-symlink "${ssd}" "${symdir}"
  264. else
  265. echo "Disk format must be either fs or block, got ${format}"
  266. fi
  267. }
  268. # Local ssds, if present, are mounted or symlinked to their appropriate
  269. # locations
  270. function ensure-local-ssds() {
  271. get-local-disk-num "scsi" "block"
  272. local scsiblocknum="${localdisknum}"
  273. local i=0
  274. for ssd in /dev/disk/by-id/google-local-ssd-*; do
  275. if [ -e "${ssd}" ]; then
  276. local devicenum=`echo ${ssd} | sed -e 's/\/dev\/disk\/by-id\/google-local-ssd-\([0-9]*\)/\1/'`
  277. if [[ "${i}" -lt "${scsiblocknum}" ]]; then
  278. mount-ext "${ssd}" "${devicenum}" "scsi" "block"
  279. else
  280. # GKE does not set NODE_LOCAL_SSDS so all non-block devices
  281. # are assumed to be filesystem devices
  282. mount-ext "${ssd}" "${devicenum}" "scsi" "fs"
  283. fi
  284. i=$((i+1))
  285. else
  286. echo "No local SCSI SSD disks found."
  287. fi
  288. done
  289. # The following mounts or symlinks NVMe devices
  290. get-local-disk-num "nvme" "block"
  291. local nvmeblocknum="${localdisknum}"
  292. local i=0
  293. for ssd in /dev/nvme*; do
  294. if [ -e "${ssd}" ]; then
  295. # This workaround to find if the NVMe device is a disk is required because
  296. # the existing Google images does not expose NVMe devices in /dev/disk/by-id
  297. if [[ `udevadm info --query=property --name=${ssd} | grep DEVTYPE | sed "s/DEVTYPE=//"` == "disk" ]]; then
  298. local devicenum=`echo ${ssd} | sed -e 's/\/dev\/nvme0n\([0-9]*\)/\1/'`
  299. if [[ "${i}" -lt "${nvmeblocknum}" ]]; then
  300. mount-ext "${ssd}" "${devicenum}" "nvme" "block"
  301. else
  302. mount-ext "${ssd}" "${devicenum}" "nvme" "fs"
  303. fi
  304. i=$((i+1))
  305. fi
  306. else
  307. echo "No local NVMe SSD disks found."
  308. fi
  309. done
  310. }
  311. # Installs logrotate configuration files
  312. function setup-logrotate() {
  313. mkdir -p /etc/logrotate.d/
  314. # Configure log rotation for all logs in /var/log, which is where k8s services
  315. # are configured to write their log files. Whenever logrotate is ran, this
  316. # config will:
  317. # * rotate the log file if its size is > 100Mb OR if one day has elapsed
  318. # * save rotated logs into a gzipped timestamped backup
  319. # * log file timestamp (controlled by 'dateformat') includes seconds too. This
  320. # ensures that logrotate can generate unique logfiles during each rotation
  321. # (otherwise it skips rotation if 'maxsize' is reached multiple times in a
  322. # day).
  323. # * keep only 5 old (rotated) logs, and will discard older logs.
  324. cat > /etc/logrotate.d/allvarlogs <<EOF
  325. /var/log/*.log {
  326. rotate ${LOGROTATE_FILES_MAX_COUNT:-5}
  327. copytruncate
  328. missingok
  329. notifempty
  330. compress
  331. maxsize ${LOGROTATE_MAX_SIZE:-100M}
  332. daily
  333. dateext
  334. dateformat -%Y%m%d-%s
  335. create 0644 root root
  336. }
  337. EOF
  338. # Configure log rotation for pod logs in /var/log/pods/NAMESPACE_NAME_UID.
  339. cat > /etc/logrotate.d/allpodlogs <<EOF
  340. /var/log/pods/*/*.log {
  341. rotate ${POD_LOG_MAX_FILE:-5}
  342. copytruncate
  343. missingok
  344. notifempty
  345. compress
  346. maxsize ${POD_LOG_MAX_SIZE:-5M}
  347. daily
  348. dateext
  349. dateformat -%Y%m%d-%s
  350. create 0644 root root
  351. }
  352. EOF
  353. }
  354. # Finds the master PD device; returns it in MASTER_PD_DEVICE
  355. function find-master-pd {
  356. MASTER_PD_DEVICE=""
  357. if [[ ! -e /dev/disk/by-id/google-master-pd ]]; then
  358. return
  359. fi
  360. device_info=$(ls -l /dev/disk/by-id/google-master-pd)
  361. relative_path=${device_info##* }
  362. MASTER_PD_DEVICE="/dev/disk/by-id/${relative_path}"
  363. }
  364. # Mounts a persistent disk (formatting if needed) to store the persistent data
  365. # on the master -- etcd's data, a few settings, and security certs/keys/tokens.
  366. # safe-format-and-mount only formats an unformatted disk, and mkdir -p will
  367. # leave a directory be if it already exists.
  368. function mount-master-pd {
  369. find-master-pd
  370. if [[ -z "${MASTER_PD_DEVICE:-}" ]]; then
  371. return
  372. fi
  373. echo "Mounting master-pd"
  374. local -r pd_path="/dev/disk/by-id/google-master-pd"
  375. local -r mount_point="/mnt/disks/master-pd"
  376. # Format and mount the disk, create directories on it for all of the master's
  377. # persistent data, and link them to where they're used.
  378. mkdir -p "${mount_point}"
  379. safe-format-and-mount "${pd_path}" "${mount_point}"
  380. echo "Mounted master-pd '${pd_path}' at '${mount_point}'"
  381. # NOTE: These locations on the PD store persistent data, so to maintain
  382. # upgradeability, these locations should not change. If they do, take care
  383. # to maintain a migration path from these locations to whatever new
  384. # locations.
  385. # Contains all the data stored in etcd.
  386. mkdir -m 700 -p "${mount_point}/var/etcd"
  387. ln -s -f "${mount_point}/var/etcd" /var/etcd
  388. mkdir -p /etc/srv
  389. # Contains the dynamically generated apiserver auth certs and keys.
  390. mkdir -p "${mount_point}/srv/kubernetes"
  391. ln -s -f "${mount_point}/srv/kubernetes" /etc/srv/kubernetes
  392. # Directory for kube-apiserver to store SSH key (if necessary).
  393. mkdir -p "${mount_point}/srv/sshproxy"
  394. ln -s -f "${mount_point}/srv/sshproxy" /etc/srv/sshproxy
  395. if ! id etcd &>/dev/null; then
  396. useradd -s /sbin/nologin -d /var/etcd etcd
  397. fi
  398. chown -R etcd "${mount_point}/var/etcd"
  399. chgrp -R etcd "${mount_point}/var/etcd"
  400. }
  401. # append_or_replace_prefixed_line ensures:
  402. # 1. the specified file exists
  403. # 2. existing lines with the specified ${prefix} are removed
  404. # 3. a new line with the specified ${prefix}${suffix} is appended
  405. function append_or_replace_prefixed_line {
  406. local -r file="${1:-}"
  407. local -r prefix="${2:-}"
  408. local -r suffix="${3:-}"
  409. local -r dirname="$(dirname ${file})"
  410. local -r tmpfile="$(mktemp -t filtered.XXXX --tmpdir=${dirname})"
  411. touch "${file}"
  412. awk "substr(\$0,0,length(\"${prefix}\")) != \"${prefix}\" { print }" "${file}" > "${tmpfile}"
  413. echo "${prefix}${suffix}" >> "${tmpfile}"
  414. mv "${tmpfile}" "${file}"
  415. }
  416. function write-pki-data {
  417. local data="${1}"
  418. local path="${2}"
  419. (umask 077; echo "${data}" | base64 --decode > "${path}")
  420. }
  421. function create-node-pki {
  422. echo "Creating node pki files"
  423. local -r pki_dir="/etc/srv/kubernetes/pki"
  424. mkdir -p "${pki_dir}"
  425. if [[ -z "${CA_CERT_BUNDLE:-}" ]]; then
  426. CA_CERT_BUNDLE="${CA_CERT}"
  427. fi
  428. CA_CERT_BUNDLE_PATH="${pki_dir}/ca-certificates.crt"
  429. write-pki-data "${CA_CERT_BUNDLE}" "${CA_CERT_BUNDLE_PATH}"
  430. if [[ ! -z "${KUBELET_CERT:-}" && ! -z "${KUBELET_KEY:-}" ]]; then
  431. KUBELET_CERT_PATH="${pki_dir}/kubelet.crt"
  432. write-pki-data "${KUBELET_CERT}" "${KUBELET_CERT_PATH}"
  433. KUBELET_KEY_PATH="${pki_dir}/kubelet.key"
  434. write-pki-data "${KUBELET_KEY}" "${KUBELET_KEY_PATH}"
  435. fi
  436. }
  437. function create-master-pki {
  438. echo "Creating master pki files"
  439. local -r pki_dir="/etc/srv/kubernetes/pki"
  440. mkdir -p "${pki_dir}"
  441. CA_CERT_PATH="${pki_dir}/ca.crt"
  442. write-pki-data "${CA_CERT}" "${CA_CERT_PATH}"
  443. # this is not true on GKE
  444. if [[ ! -z "${CA_KEY:-}" ]]; then
  445. CA_KEY_PATH="${pki_dir}/ca.key"
  446. write-pki-data "${CA_KEY}" "${CA_KEY_PATH}"
  447. fi
  448. if [[ -z "${APISERVER_SERVER_CERT:-}" || -z "${APISERVER_SERVER_KEY:-}" ]]; then
  449. APISERVER_SERVER_CERT="${MASTER_CERT}"
  450. APISERVER_SERVER_KEY="${MASTER_KEY}"
  451. fi
  452. APISERVER_SERVER_CERT_PATH="${pki_dir}/apiserver.crt"
  453. write-pki-data "${APISERVER_SERVER_CERT}" "${APISERVER_SERVER_CERT_PATH}"
  454. APISERVER_SERVER_KEY_PATH="${pki_dir}/apiserver.key"
  455. write-pki-data "${APISERVER_SERVER_KEY}" "${APISERVER_SERVER_KEY_PATH}"
  456. if [[ -z "${APISERVER_CLIENT_CERT:-}" || -z "${APISERVER_CLIENT_KEY:-}" ]]; then
  457. APISERVER_CLIENT_CERT="${KUBEAPISERVER_CERT}"
  458. APISERVER_CLIENT_KEY="${KUBEAPISERVER_KEY}"
  459. fi
  460. APISERVER_CLIENT_CERT_PATH="${pki_dir}/apiserver-client.crt"
  461. write-pki-data "${APISERVER_CLIENT_CERT}" "${APISERVER_CLIENT_CERT_PATH}"
  462. APISERVER_CLIENT_KEY_PATH="${pki_dir}/apiserver-client.key"
  463. write-pki-data "${APISERVER_CLIENT_KEY}" "${APISERVER_CLIENT_KEY_PATH}"
  464. if [[ -z "${SERVICEACCOUNT_CERT:-}" || -z "${SERVICEACCOUNT_KEY:-}" ]]; then
  465. SERVICEACCOUNT_CERT="${MASTER_CERT}"
  466. SERVICEACCOUNT_KEY="${MASTER_KEY}"
  467. fi
  468. SERVICEACCOUNT_CERT_PATH="${pki_dir}/serviceaccount.crt"
  469. write-pki-data "${SERVICEACCOUNT_CERT}" "${SERVICEACCOUNT_CERT_PATH}"
  470. SERVICEACCOUNT_KEY_PATH="${pki_dir}/serviceaccount.key"
  471. write-pki-data "${SERVICEACCOUNT_KEY}" "${SERVICEACCOUNT_KEY_PATH}"
  472. if [[ ! -z "${REQUESTHEADER_CA_CERT:-}" ]]; then
  473. AGGREGATOR_CA_KEY_PATH="${pki_dir}/aggr_ca.key"
  474. write-pki-data "${AGGREGATOR_CA_KEY}" "${AGGREGATOR_CA_KEY_PATH}"
  475. REQUESTHEADER_CA_CERT_PATH="${pki_dir}/aggr_ca.crt"
  476. write-pki-data "${REQUESTHEADER_CA_CERT}" "${REQUESTHEADER_CA_CERT_PATH}"
  477. PROXY_CLIENT_KEY_PATH="${pki_dir}/proxy_client.key"
  478. write-pki-data "${PROXY_CLIENT_KEY}" "${PROXY_CLIENT_KEY_PATH}"
  479. PROXY_CLIENT_CERT_PATH="${pki_dir}/proxy_client.crt"
  480. write-pki-data "${PROXY_CLIENT_CERT}" "${PROXY_CLIENT_CERT_PATH}"
  481. fi
  482. }
  483. # After the first boot and on upgrade, these files exist on the master-pd
  484. # and should never be touched again (except perhaps an additional service
  485. # account, see NB below.) One exception is if METADATA_CLOBBERS_CONFIG is
  486. # enabled. In that case the basic_auth.csv file will be rewritten to make
  487. # sure it matches the metadata source of truth.
  488. function create-master-auth {
  489. echo "Creating master auth files"
  490. local -r auth_dir="/etc/srv/kubernetes"
  491. local -r basic_auth_csv="${auth_dir}/basic_auth.csv"
  492. if [[ -n "${KUBE_PASSWORD:-}" && -n "${KUBE_USER:-}" ]]; then
  493. if [[ -e "${basic_auth_csv}" && "${METADATA_CLOBBERS_CONFIG:-false}" == "true" ]]; then
  494. # If METADATA_CLOBBERS_CONFIG is true, we want to rewrite the file
  495. # completely, because if we're changing KUBE_USER and KUBE_PASSWORD, we
  496. # have nothing to match on. The file is replaced just below with
  497. # append_or_replace_prefixed_line.
  498. rm "${basic_auth_csv}"
  499. fi
  500. append_or_replace_prefixed_line "${basic_auth_csv}" "${KUBE_PASSWORD},${KUBE_USER}," "admin,system:masters"
  501. fi
  502. local -r known_tokens_csv="${auth_dir}/known_tokens.csv"
  503. if [[ -e "${known_tokens_csv}" && "${METADATA_CLOBBERS_CONFIG:-false}" == "true" ]]; then
  504. rm "${known_tokens_csv}"
  505. fi
  506. if [[ -n "${KUBE_BEARER_TOKEN:-}" ]]; then
  507. append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_BEARER_TOKEN}," "admin,admin,system:masters"
  508. fi
  509. if [[ -n "${KUBE_BOOTSTRAP_TOKEN:-}" ]]; then
  510. append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_BOOTSTRAP_TOKEN}," "gcp:kube-bootstrap,uid:gcp:kube-bootstrap,system:masters"
  511. fi
  512. if [[ -n "${KUBE_CONTROLLER_MANAGER_TOKEN:-}" ]]; then
  513. append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_CONTROLLER_MANAGER_TOKEN}," "system:kube-controller-manager,uid:system:kube-controller-manager"
  514. fi
  515. if [[ -n "${KUBE_SCHEDULER_TOKEN:-}" ]]; then
  516. append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_SCHEDULER_TOKEN}," "system:kube-scheduler,uid:system:kube-scheduler"
  517. fi
  518. if [[ -n "${KUBE_CLUSTER_AUTOSCALER_TOKEN:-}" ]]; then
  519. append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_CLUSTER_AUTOSCALER_TOKEN}," "cluster-autoscaler,uid:cluster-autoscaler"
  520. fi
  521. if [[ -n "${KUBE_PROXY_TOKEN:-}" ]]; then
  522. append_or_replace_prefixed_line "${known_tokens_csv}" "${KUBE_PROXY_TOKEN}," "system:kube-proxy,uid:kube_proxy"
  523. fi
  524. if [[ -n "${NODE_PROBLEM_DETECTOR_TOKEN:-}" ]]; then
  525. append_or_replace_prefixed_line "${known_tokens_csv}" "${NODE_PROBLEM_DETECTOR_TOKEN}," "system:node-problem-detector,uid:node-problem-detector"
  526. fi
  527. if [[ -n "${GCE_GLBC_TOKEN:-}" ]]; then
  528. append_or_replace_prefixed_line "${known_tokens_csv}" "${GCE_GLBC_TOKEN}," "system:controller:glbc,uid:system:controller:glbc"
  529. fi
  530. if [[ -n "${ADDON_MANAGER_TOKEN:-}" ]]; then
  531. append_or_replace_prefixed_line "${known_tokens_csv}" "${ADDON_MANAGER_TOKEN}," "system:addon-manager,uid:system:addon-manager,system:masters"
  532. fi
  533. if [[ -n "${EXTRA_STATIC_AUTH_COMPONENTS:-}" ]]; then
  534. # Create a static Bearer token and kubeconfig for extra, comma-separated components.
  535. IFS="," read -r -a extra_components <<< "${EXTRA_STATIC_AUTH_COMPONENTS:-}"
  536. for extra_component in "${extra_components[@]}"; do
  537. local token="$(secure_random 32)"
  538. append_or_replace_prefixed_line "${known_tokens_csv}" "${token}," "system:${extra_component},uid:system:${extra_component}"
  539. create-kubeconfig "${extra_component}" "${token}"
  540. done
  541. fi
  542. local use_cloud_config="false"
  543. cat <<EOF >/etc/gce.conf
  544. [global]
  545. EOF
  546. if [[ -n "${GCE_API_ENDPOINT:-}" ]]; then
  547. cat <<EOF >>/etc/gce.conf
  548. api-endpoint = ${GCE_API_ENDPOINT}
  549. EOF
  550. fi
  551. if [[ -n "${TOKEN_URL:-}" && -n "${TOKEN_BODY:-}" ]]; then
  552. use_cloud_config="true"
  553. cat <<EOF >>/etc/gce.conf
  554. token-url = ${TOKEN_URL}
  555. token-body = ${TOKEN_BODY}
  556. EOF
  557. fi
  558. if [[ -n "${CONTAINER_API_ENDPOINT:-}" ]]; then
  559. use_cloud_config="true"
  560. cat <<EOF >>/etc/gce.conf
  561. container-api-endpoint = ${CONTAINER_API_ENDPOINT}
  562. EOF
  563. fi
  564. if [[ -n "${PROJECT_ID:-}" ]]; then
  565. use_cloud_config="true"
  566. cat <<EOF >>/etc/gce.conf
  567. project-id = ${PROJECT_ID}
  568. EOF
  569. fi
  570. if [[ -n "${NETWORK_PROJECT_ID:-}" ]]; then
  571. use_cloud_config="true"
  572. cat <<EOF >>/etc/gce.conf
  573. network-project-id = ${NETWORK_PROJECT_ID}
  574. EOF
  575. fi
  576. if [[ -n "${NODE_NETWORK:-}" ]]; then
  577. use_cloud_config="true"
  578. cat <<EOF >>/etc/gce.conf
  579. network-name = ${NODE_NETWORK}
  580. EOF
  581. fi
  582. if [[ -n "${NODE_SUBNETWORK:-}" ]]; then
  583. use_cloud_config="true"
  584. cat <<EOF >>/etc/gce.conf
  585. subnetwork-name = ${NODE_SUBNETWORK}
  586. EOF
  587. fi
  588. if [[ -n "${NODE_INSTANCE_PREFIX:-}" ]]; then
  589. use_cloud_config="true"
  590. if [[ -n "${NODE_TAGS:-}" ]]; then
  591. # split NODE_TAGS into an array by comma.
  592. IFS=',' read -r -a node_tags <<< ${NODE_TAGS}
  593. else
  594. local -r node_tags="${NODE_INSTANCE_PREFIX}"
  595. fi
  596. cat <<EOF >>/etc/gce.conf
  597. node-instance-prefix = ${NODE_INSTANCE_PREFIX}
  598. EOF
  599. for tag in ${node_tags[@]}; do
  600. cat <<EOF >>/etc/gce.conf
  601. node-tags = ${tag}
  602. EOF
  603. done
  604. fi
  605. if [[ -n "${MULTIZONE:-}" ]]; then
  606. use_cloud_config="true"
  607. cat <<EOF >>/etc/gce.conf
  608. multizone = ${MULTIZONE}
  609. EOF
  610. fi
  611. # Multimaster indicates that the cluster is HA.
  612. # Currently the only HA clusters are regional.
  613. # If we introduce zonal multimaster this will need to be revisited.
  614. if [[ -n "${MULTIMASTER:-}" ]]; then
  615. use_cloud_config="true"
  616. cat <<EOF >>/etc/gce.conf
  617. regional = ${MULTIMASTER}
  618. EOF
  619. fi
  620. if [[ -n "${GCE_ALPHA_FEATURES:-}" ]]; then
  621. use_cloud_config="true"
  622. # split GCE_ALPHA_FEATURES into an array by comma.
  623. IFS=',' read -r -a alpha_features <<< ${GCE_ALPHA_FEATURES}
  624. for feature in ${alpha_features[@]}; do
  625. cat <<EOF >>/etc/gce.conf
  626. alpha-features = ${feature}
  627. EOF
  628. done
  629. fi
  630. if [[ -n "${SECONDARY_RANGE_NAME:-}" ]]; then
  631. use_cloud_config="true"
  632. cat <<EOF >> /etc/gce.conf
  633. secondary-range-name = ${SECONDARY_RANGE_NAME}
  634. EOF
  635. fi
  636. if [[ "${use_cloud_config}" != "true" ]]; then
  637. rm -f /etc/gce.conf
  638. fi
  639. if [[ -n "${GCP_AUTHN_URL:-}" ]]; then
  640. cat <<EOF >/etc/gcp_authn.config
  641. clusters:
  642. - name: gcp-authentication-server
  643. cluster:
  644. server: ${GCP_AUTHN_URL}
  645. users:
  646. - name: kube-apiserver
  647. user:
  648. auth-provider:
  649. name: gcp
  650. current-context: webhook
  651. contexts:
  652. - context:
  653. cluster: gcp-authentication-server
  654. user: kube-apiserver
  655. name: webhook
  656. EOF
  657. fi
  658. if [[ -n "${GCP_AUTHZ_URL:-}" ]]; then
  659. cat <<EOF >/etc/gcp_authz.config
  660. clusters:
  661. - name: gcp-authorization-server
  662. cluster:
  663. server: ${GCP_AUTHZ_URL}
  664. users:
  665. - name: kube-apiserver
  666. user:
  667. auth-provider:
  668. name: gcp
  669. current-context: webhook
  670. contexts:
  671. - context:
  672. cluster: gcp-authorization-server
  673. user: kube-apiserver
  674. name: webhook
  675. EOF
  676. fi
  677. if [[ -n "${GCP_IMAGE_VERIFICATION_URL:-}" ]]; then
  678. # This is the config file for the image review webhook.
  679. cat <<EOF >/etc/gcp_image_review.config
  680. clusters:
  681. - name: gcp-image-review-server
  682. cluster:
  683. server: ${GCP_IMAGE_VERIFICATION_URL}
  684. users:
  685. - name: kube-apiserver
  686. user:
  687. auth-provider:
  688. name: gcp
  689. current-context: webhook
  690. contexts:
  691. - context:
  692. cluster: gcp-image-review-server
  693. user: kube-apiserver
  694. name: webhook
  695. EOF
  696. # This is the config for the image review admission controller.
  697. cat <<EOF >/etc/admission_controller.config
  698. imagePolicy:
  699. kubeConfigFile: /etc/gcp_image_review.config
  700. allowTTL: 30
  701. denyTTL: 30
  702. retryBackoff: 500
  703. defaultAllow: true
  704. EOF
  705. fi
  706. }
  707. # Write the config for the audit policy.
  708. function create-master-audit-policy {
  709. local -r path="${1}"
  710. local -r policy="${2:-}"
  711. if [[ -n "${policy}" ]]; then
  712. echo "${policy}" > "${path}"
  713. return
  714. fi
  715. # Known api groups
  716. local -r known_apis='
  717. - group: "" # core
  718. - group: "admissionregistration.k8s.io"
  719. - group: "apiextensions.k8s.io"
  720. - group: "apiregistration.k8s.io"
  721. - group: "apps"
  722. - group: "authentication.k8s.io"
  723. - group: "authorization.k8s.io"
  724. - group: "autoscaling"
  725. - group: "batch"
  726. - group: "certificates.k8s.io"
  727. - group: "extensions"
  728. - group: "metrics.k8s.io"
  729. - group: "networking.k8s.io"
  730. - group: "node.k8s.io"
  731. - group: "policy"
  732. - group: "rbac.authorization.k8s.io"
  733. - group: "scheduling.k8s.io"
  734. - group: "settings.k8s.io"
  735. - group: "storage.k8s.io"'
  736. cat <<EOF >"${path}"
  737. apiVersion: audit.k8s.io/v1
  738. kind: Policy
  739. rules:
  740. # The following requests were manually identified as high-volume and low-risk,
  741. # so drop them.
  742. - level: None
  743. users: ["system:kube-proxy"]
  744. verbs: ["watch"]
  745. resources:
  746. - group: "" # core
  747. resources: ["endpoints", "services", "services/status"]
  748. - level: None
  749. # Ingress controller reads 'configmaps/ingress-uid' through the unsecured port.
  750. # TODO(#46983): Change this to the ingress controller service account.
  751. users: ["system:unsecured"]
  752. namespaces: ["kube-system"]
  753. verbs: ["get"]
  754. resources:
  755. - group: "" # core
  756. resources: ["configmaps"]
  757. - level: None
  758. users: ["kubelet"] # legacy kubelet identity
  759. verbs: ["get"]
  760. resources:
  761. - group: "" # core
  762. resources: ["nodes", "nodes/status"]
  763. - level: None
  764. userGroups: ["system:nodes"]
  765. verbs: ["get"]
  766. resources:
  767. - group: "" # core
  768. resources: ["nodes", "nodes/status"]
  769. - level: None
  770. users:
  771. - system:kube-controller-manager
  772. - system:kube-scheduler
  773. - system:serviceaccount:kube-system:endpoint-controller
  774. verbs: ["get", "update"]
  775. namespaces: ["kube-system"]
  776. resources:
  777. - group: "" # core
  778. resources: ["endpoints"]
  779. - level: None
  780. users: ["system:apiserver"]
  781. verbs: ["get"]
  782. resources:
  783. - group: "" # core
  784. resources: ["namespaces", "namespaces/status", "namespaces/finalize"]
  785. - level: None
  786. users: ["cluster-autoscaler"]
  787. verbs: ["get", "update"]
  788. namespaces: ["kube-system"]
  789. resources:
  790. - group: "" # core
  791. resources: ["configmaps", "endpoints"]
  792. # Don't log HPA fetching metrics.
  793. - level: None
  794. users:
  795. - system:kube-controller-manager
  796. verbs: ["get", "list"]
  797. resources:
  798. - group: "metrics.k8s.io"
  799. # Don't log these read-only URLs.
  800. - level: None
  801. nonResourceURLs:
  802. - /healthz*
  803. - /version
  804. - /swagger*
  805. # Don't log events requests.
  806. - level: None
  807. resources:
  808. - group: "" # core
  809. resources: ["events"]
  810. # node and pod status calls from nodes are high-volume and can be large, don't log responses for expected updates from nodes
  811. - level: Request
  812. users: ["kubelet", "system:node-problem-detector", "system:serviceaccount:kube-system:node-problem-detector"]
  813. verbs: ["update","patch"]
  814. resources:
  815. - group: "" # core
  816. resources: ["nodes/status", "pods/status"]
  817. omitStages:
  818. - "RequestReceived"
  819. - level: Request
  820. userGroups: ["system:nodes"]
  821. verbs: ["update","patch"]
  822. resources:
  823. - group: "" # core
  824. resources: ["nodes/status", "pods/status"]
  825. omitStages:
  826. - "RequestReceived"
  827. # deletecollection calls can be large, don't log responses for expected namespace deletions
  828. - level: Request
  829. users: ["system:serviceaccount:kube-system:namespace-controller"]
  830. verbs: ["deletecollection"]
  831. omitStages:
  832. - "RequestReceived"
  833. # Secrets, ConfigMaps, and TokenReviews can contain sensitive & binary data,
  834. # so only log at the Metadata level.
  835. - level: Metadata
  836. resources:
  837. - group: "" # core
  838. resources: ["secrets", "configmaps"]
  839. - group: authentication.k8s.io
  840. resources: ["tokenreviews"]
  841. omitStages:
  842. - "RequestReceived"
  843. # Get repsonses can be large; skip them.
  844. - level: Request
  845. verbs: ["get", "list", "watch"]
  846. resources: ${known_apis}
  847. omitStages:
  848. - "RequestReceived"
  849. # Default level for known APIs
  850. - level: RequestResponse
  851. resources: ${known_apis}
  852. omitStages:
  853. - "RequestReceived"
  854. # Default level for all other requests.
  855. - level: Metadata
  856. omitStages:
  857. - "RequestReceived"
  858. EOF
  859. }
  860. # Writes the configuration file used by the webhook advanced auditing backend.
  861. function create-master-audit-webhook-config {
  862. local -r path="${1}"
  863. if [[ -n "${GCP_AUDIT_URL:-}" ]]; then
  864. # The webhook config file is a kubeconfig file describing the webhook endpoint.
  865. cat <<EOF >"${path}"
  866. clusters:
  867. - name: gcp-audit-server
  868. cluster:
  869. server: ${GCP_AUDIT_URL}
  870. users:
  871. - name: kube-apiserver
  872. user:
  873. auth-provider:
  874. name: gcp
  875. current-context: webhook
  876. contexts:
  877. - context:
  878. cluster: gcp-audit-server
  879. user: kube-apiserver
  880. name: webhook
  881. EOF
  882. fi
  883. }
  884. function create-kubeconfig {
  885. local component=$1
  886. local token=$2
  887. echo "Creating kubeconfig file for component ${component}"
  888. mkdir -p /etc/srv/kubernetes/${component}
  889. cat <<EOF >/etc/srv/kubernetes/${component}/kubeconfig
  890. apiVersion: v1
  891. kind: Config
  892. users:
  893. - name: ${component}
  894. user:
  895. token: ${token}
  896. clusters:
  897. - name: local
  898. cluster:
  899. insecure-skip-tls-verify: true
  900. server: https://localhost:443
  901. contexts:
  902. - context:
  903. cluster: local
  904. user: ${component}
  905. name: ${component}
  906. current-context: ${component}
  907. EOF
  908. }
  909. # Arg 1: the IP address of the API server
  910. function create-kubelet-kubeconfig() {
  911. local apiserver_address="${1}"
  912. if [[ -z "${apiserver_address}" ]]; then
  913. echo "Must provide API server address to create Kubelet kubeconfig file!"
  914. exit 1
  915. fi
  916. if [[ "${CREATE_BOOTSTRAP_KUBECONFIG:-true}" == "true" ]]; then
  917. echo "Creating kubelet bootstrap-kubeconfig file"
  918. cat <<EOF >/var/lib/kubelet/bootstrap-kubeconfig
  919. apiVersion: v1
  920. kind: Config
  921. users:
  922. - name: kubelet
  923. user:
  924. client-certificate: ${KUBELET_CERT_PATH}
  925. client-key: ${KUBELET_KEY_PATH}
  926. clusters:
  927. - name: local
  928. cluster:
  929. server: https://${apiserver_address}
  930. certificate-authority: ${CA_CERT_BUNDLE_PATH}
  931. contexts:
  932. - context:
  933. cluster: local
  934. user: kubelet
  935. name: service-account-context
  936. current-context: service-account-context
  937. EOF
  938. elif [[ "${FETCH_BOOTSTRAP_KUBECONFIG:-false}" == "true" ]]; then
  939. echo "Fetching kubelet bootstrap-kubeconfig file from metadata"
  940. get-metadata-value "instance/attributes/bootstrap-kubeconfig" >/var/lib/kubelet/bootstrap-kubeconfig
  941. else
  942. echo "Fetching kubelet kubeconfig file from metadata"
  943. get-metadata-value "instance/attributes/kubeconfig" >/var/lib/kubelet/kubeconfig
  944. fi
  945. }
  946. # Uses KUBELET_CA_CERT (falling back to CA_CERT), KUBELET_CERT, and KUBELET_KEY
  947. # to generate a kubeconfig file for the kubelet to securely connect to the apiserver.
  948. # Set REGISTER_MASTER_KUBELET to true if kubelet on the master node
  949. # should register to the apiserver.
  950. function create-master-kubelet-auth {
  951. # Only configure the kubelet on the master if the required variables are
  952. # set in the environment.
  953. if [[ -n "${KUBELET_APISERVER:-}" && -n "${KUBELET_CERT:-}" && -n "${KUBELET_KEY:-}" ]]; then
  954. REGISTER_MASTER_KUBELET="true"
  955. create-kubelet-kubeconfig ${KUBELET_APISERVER}
  956. fi
  957. }
  958. function create-kubeproxy-user-kubeconfig {
  959. echo "Creating kube-proxy user kubeconfig file"
  960. cat <<EOF >/var/lib/kube-proxy/kubeconfig
  961. apiVersion: v1
  962. kind: Config
  963. users:
  964. - name: kube-proxy
  965. user:
  966. token: ${KUBE_PROXY_TOKEN}
  967. clusters:
  968. - name: local
  969. cluster:
  970. certificate-authority-data: ${CA_CERT_BUNDLE}
  971. contexts:
  972. - context:
  973. cluster: local
  974. user: kube-proxy
  975. name: service-account-context
  976. current-context: service-account-context
  977. EOF
  978. }
  979. function create-kubescheduler-policy-config {
  980. echo "Creating kube-scheduler policy config file"
  981. mkdir -p /etc/srv/kubernetes/kube-scheduler
  982. cat <<EOF >/etc/srv/kubernetes/kube-scheduler/policy-config
  983. ${SCHEDULER_POLICY_CONFIG}
  984. EOF
  985. }
  986. function create-node-problem-detector-kubeconfig {
  987. local apiserver_address="${1}"
  988. if [[ -z "${apiserver_address}" ]]; then
  989. echo "Must provide API server address to create node-problem-detector kubeconfig file!"
  990. exit 1
  991. fi
  992. echo "Creating node-problem-detector kubeconfig file"
  993. mkdir -p /var/lib/node-problem-detector
  994. cat <<EOF >/var/lib/node-problem-detector/kubeconfig
  995. apiVersion: v1
  996. kind: Config
  997. users:
  998. - name: node-problem-detector
  999. user:
  1000. token: ${NODE_PROBLEM_DETECTOR_TOKEN}
  1001. clusters:
  1002. - name: local
  1003. cluster:
  1004. server: https://${apiserver_address}
  1005. certificate-authority-data: ${CA_CERT}
  1006. contexts:
  1007. - context:
  1008. cluster: local
  1009. user: node-problem-detector
  1010. name: service-account-context
  1011. current-context: service-account-context
  1012. EOF
  1013. }
  1014. function create-master-etcd-auth {
  1015. if [[ -n "${ETCD_CA_CERT:-}" && -n "${ETCD_PEER_KEY:-}" && -n "${ETCD_PEER_CERT:-}" ]]; then
  1016. local -r auth_dir="/etc/srv/kubernetes"
  1017. echo "${ETCD_CA_CERT}" | base64 --decode | gunzip > "${auth_dir}/etcd-ca.crt"
  1018. echo "${ETCD_PEER_KEY}" | base64 --decode > "${auth_dir}/etcd-peer.key"
  1019. echo "${ETCD_PEER_CERT}" | base64 --decode | gunzip > "${auth_dir}/etcd-peer.crt"
  1020. fi
  1021. }
  1022. function create-master-etcd-apiserver-auth {
  1023. if [[ -n "${ETCD_APISERVER_CA_CERT:-}" && -n "${ETCD_APISERVER_SERVER_KEY:-}" && -n "${ETCD_APISERVER_SERVER_CERT:-}" && -n "${ETCD_APISERVER_CLIENT_KEY:-}" && -n "${ETCD_APISERVER_CLIENT_CERT:-}" ]]; then
  1024. local -r auth_dir="/etc/srv/kubernetes/pki"
  1025. ETCD_APISERVER_CA_KEY_PATH="${auth_dir}/etcd-apiserver-ca.key"
  1026. echo "${ETCD_APISERVER_CA_KEY}" | base64 --decode > "${ETCD_APISERVER_CA_KEY_PATH}"
  1027. ETCD_APISERVER_CA_CERT_PATH="${auth_dir}/etcd-apiserver-ca.crt"
  1028. echo "${ETCD_APISERVER_CA_CERT}" | base64 --decode | gunzip > "${ETCD_APISERVER_CA_CERT_PATH}"
  1029. ETCD_APISERVER_SERVER_KEY_PATH="${auth_dir}/etcd-apiserver-server.key"
  1030. echo "${ETCD_APISERVER_SERVER_KEY}" | base64 --decode > "${ETCD_APISERVER_SERVER_KEY_PATH}"
  1031. ETCD_APISERVER_SERVER_CERT_PATH="${auth_dir}/etcd-apiserver-server.crt"
  1032. echo "${ETCD_APISERVER_SERVER_CERT}" | base64 --decode | gunzip > "${ETCD_APISERVER_SERVER_CERT_PATH}"
  1033. ETCD_APISERVER_CLIENT_KEY_PATH="${auth_dir}/etcd-apiserver-client.key"
  1034. echo "${ETCD_APISERVER_CLIENT_KEY}" | base64 --decode > "${ETCD_APISERVER_CLIENT_KEY_PATH}"
  1035. ETCD_APISERVER_CLIENT_CERT_PATH="${auth_dir}/etcd-apiserver-client.crt"
  1036. echo "${ETCD_APISERVER_CLIENT_CERT}" | base64 --decode | gunzip > "${ETCD_APISERVER_CLIENT_CERT_PATH}"
  1037. fi
  1038. }
  1039. function assemble-docker-flags {
  1040. echo "Assemble docker command line flags"
  1041. local docker_opts="-p /var/run/docker.pid --iptables=false --ip-masq=false"
  1042. if [[ "${TEST_CLUSTER:-}" == "true" ]]; then
  1043. docker_opts+=" --log-level=debug"
  1044. else
  1045. docker_opts+=" --log-level=warn"
  1046. fi
  1047. local use_net_plugin="true"
  1048. if [[ "${NETWORK_PROVIDER:-}" == "kubenet" || "${NETWORK_PROVIDER:-}" == "cni" ]]; then
  1049. # set docker0 cidr to private ip address range to avoid conflict with cbr0 cidr range
  1050. docker_opts+=" --bip=169.254.123.1/24"
  1051. else
  1052. use_net_plugin="false"
  1053. docker_opts+=" --bridge=cbr0"
  1054. fi
  1055. # Decide whether to enable a docker registry mirror. This is taken from
  1056. # the "kube-env" metadata value.
  1057. if [[ -n "${DOCKER_REGISTRY_MIRROR_URL:-}" ]]; then
  1058. echo "Enable docker registry mirror at: ${DOCKER_REGISTRY_MIRROR_URL}"
  1059. docker_opts+=" --registry-mirror=${DOCKER_REGISTRY_MIRROR_URL}"
  1060. fi
  1061. # Configure docker logging
  1062. docker_opts+=" --log-driver=${DOCKER_LOG_DRIVER:-json-file}"
  1063. docker_opts+=" --log-opt=max-size=${DOCKER_LOG_MAX_SIZE:-10m}"
  1064. docker_opts+=" --log-opt=max-file=${DOCKER_LOG_MAX_FILE:-5}"
  1065. # Disable live-restore if the environment variable is set.
  1066. if [[ "${DISABLE_DOCKER_LIVE_RESTORE:-false}" == "true" ]]; then
  1067. docker_opts+=" --live-restore=false"
  1068. fi
  1069. echo "DOCKER_OPTS=\"${docker_opts} ${EXTRA_DOCKER_OPTS:-}\"" > /etc/default/docker
  1070. # Ensure TasksMax is sufficient for docker.
  1071. # (https://github.com/kubernetes/kubernetes/issues/51977)
  1072. echo "Extend the docker.service configuration to set a higher pids limit"
  1073. mkdir -p /etc/systemd/system/docker.service.d
  1074. cat <<EOF >/etc/systemd/system/docker.service.d/01tasksmax.conf
  1075. [Service]
  1076. TasksMax=infinity
  1077. EOF
  1078. systemctl daemon-reload
  1079. echo "Docker command line is updated. Restart docker to pick it up"
  1080. systemctl restart docker
  1081. }
  1082. # This function assembles the kubelet systemd service file and starts it
  1083. # using systemctl.
  1084. function start-kubelet {
  1085. echo "Start kubelet"
  1086. # TODO(#60123): The kubelet should create the cert-dir directory if it doesn't exist
  1087. mkdir -p /var/lib/kubelet/pki/
  1088. local kubelet_bin="${KUBE_HOME}/bin/kubelet"
  1089. local -r version="$("${kubelet_bin}" --version=true | cut -f2 -d " ")"
  1090. local -r builtin_kubelet="/usr/bin/kubelet"
  1091. if [[ "${TEST_CLUSTER:-}" == "true" ]]; then
  1092. # Determine which binary to use on test clusters. We use the built-in
  1093. # version only if the downloaded version is the same as the built-in
  1094. # version. This allows GCI to run some of the e2e tests to qualify the
  1095. # built-in kubelet.
  1096. if [[ -x "${builtin_kubelet}" ]]; then
  1097. local -r builtin_version="$("${builtin_kubelet}" --version=true | cut -f2 -d " ")"
  1098. if [[ "${builtin_version}" == "${version}" ]]; then
  1099. kubelet_bin="${builtin_kubelet}"
  1100. fi
  1101. fi
  1102. fi
  1103. echo "Using kubelet binary at ${kubelet_bin}"
  1104. local -r kubelet_env_file="/etc/default/kubelet"
  1105. local kubelet_opts="${KUBELET_ARGS} ${KUBELET_CONFIG_FILE_ARG:-}"
  1106. echo "KUBELET_OPTS=\"${kubelet_opts}\"" > "${kubelet_env_file}"
  1107. echo "KUBE_COVERAGE_FILE=\"/var/log/kubelet.cov\"" >> "${kubelet_env_file}"
  1108. # Write the systemd service file for kubelet.
  1109. cat <<EOF >/etc/systemd/system/kubelet.service
  1110. [Unit]
  1111. Description=Kubernetes kubelet
  1112. Requires=network-online.target
  1113. After=network-online.target
  1114. [Service]
  1115. Restart=always
  1116. RestartSec=10
  1117. EnvironmentFile=${kubelet_env_file}
  1118. ExecStart=${kubelet_bin} \$KUBELET_OPTS
  1119. [Install]
  1120. WantedBy=multi-user.target
  1121. EOF
  1122. systemctl daemon-reload
  1123. systemctl start kubelet.service
  1124. }
  1125. # This function assembles the node problem detector systemd service file and
  1126. # starts it using systemctl.
  1127. function start-node-problem-detector {
  1128. echo "Start node problem detector"
  1129. local -r npd_bin="${KUBE_HOME}/bin/node-problem-detector"
  1130. echo "Using node problem detector binary at ${npd_bin}"
  1131. local flags="${NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS:-}"
  1132. if [[ -z "${flags}" ]]; then
  1133. local -r km_config="${KUBE_HOME}/node-problem-detector/config/kernel-monitor.json"
  1134. # TODO(random-liu): Handle this for alternative container runtime.
  1135. local -r dm_config="${KUBE_HOME}/node-problem-detector/config/docker-monitor.json"
  1136. local -r custom_km_config="${KUBE_HOME}/node-problem-detector/config/kernel-monitor-counter.json,${KUBE_HOME}/node-problem-detector/config/systemd-monitor-counter.json,${KUBE_HOME}/node-problem-detector/config/docker-monitor-counter.json"
  1137. flags="${NPD_TEST_LOG_LEVEL:-"--v=2"} ${NPD_TEST_ARGS:-}"
  1138. flags+=" --logtostderr"
  1139. flags+=" --system-log-monitors=${km_config},${dm_config}"
  1140. flags+=" --custom-plugin-monitors=${custom_km_config}"
  1141. local -r npd_port=${NODE_PROBLEM_DETECTOR_PORT:-20256}
  1142. flags+=" --port=${npd_port}"
  1143. if [[ -n "${EXTRA_NPD_ARGS:-}" ]]; then
  1144. flags+=" ${EXTRA_NPD_ARGS}"
  1145. fi
  1146. fi
  1147. flags+=" --apiserver-override=https://${KUBERNETES_MASTER_NAME}?inClusterConfig=false&auth=/var/lib/node-problem-detector/kubeconfig"
  1148. # Write the systemd service file for node problem detector.
  1149. cat <<EOF >/etc/systemd/system/node-problem-detector.service
  1150. [Unit]
  1151. Description=Kubernetes node problem detector
  1152. Requires=network-online.target
  1153. After=network-online.target
  1154. [Service]
  1155. Restart=always
  1156. RestartSec=10
  1157. ExecStart=${npd_bin} ${flags}
  1158. [Install]
  1159. WantedBy=multi-user.target
  1160. EOF
  1161. systemctl start node-problem-detector.service
  1162. }
  1163. # Create the log file and set its properties.
  1164. #
  1165. # $1 is the file to create.
  1166. # $2: the log owner uid to set for the log file.
  1167. # $3: the log owner gid to set for the log file.
  1168. function prepare-log-file {
  1169. touch $1
  1170. chmod 644 $1
  1171. chown "${2:-${LOG_OWNER_USER:-root}}":"${3:-${LOG_OWNER_GROUP:-root}}" $1
  1172. }
  1173. # Prepares parameters for kube-proxy manifest.
  1174. # $1 source path of kube-proxy manifest.
  1175. function prepare-kube-proxy-manifest-variables {
  1176. local -r src_file=$1;
  1177. local -r kubeconfig="--kubeconfig=/var/lib/kube-proxy/kubeconfig"
  1178. local kube_docker_registry="k8s.gcr.io"
  1179. if [[ -n "${KUBE_DOCKER_REGISTRY:-}" ]]; then
  1180. kube_docker_registry=${KUBE_DOCKER_REGISTRY}
  1181. fi
  1182. local -r kube_proxy_docker_tag=$(cat /home/kubernetes/kube-docker-files/kube-proxy.docker_tag)
  1183. local api_servers="--master=https://${KUBERNETES_MASTER_NAME}"
  1184. local params="${KUBEPROXY_TEST_LOG_LEVEL:-"--v=2"}"
  1185. if [[ -n "${FEATURE_GATES:-}" ]]; then
  1186. params+=" --feature-gates=${FEATURE_GATES}"
  1187. fi
  1188. if [[ "${KUBE_PROXY_MODE:-}" == "ipvs" ]];then
  1189. sudo modprobe -a ip_vs ip_vs_rr ip_vs_wrr ip_vs_sh nf_conntrack_ipv4
  1190. if [[ $? -eq 0 ]];
  1191. then
  1192. params+=" --proxy-mode=ipvs"
  1193. else
  1194. # If IPVS modules are not present, make sure the node does not come up as
  1195. # healthy.
  1196. exit 1
  1197. fi
  1198. fi
  1199. params+=" --iptables-sync-period=1m --iptables-min-sync-period=10s --ipvs-sync-period=1m --ipvs-min-sync-period=10s"
  1200. if [[ -n "${KUBEPROXY_TEST_ARGS:-}" ]]; then
  1201. params+=" ${KUBEPROXY_TEST_ARGS}"
  1202. fi
  1203. local container_env=""
  1204. local kube_cache_mutation_detector_env_name=""
  1205. local kube_cache_mutation_detector_env_value=""
  1206. if [[ -n "${ENABLE_CACHE_MUTATION_DETECTOR:-}" ]]; then
  1207. container_env="env:"
  1208. kube_cache_mutation_detector_env_name="- name: KUBE_CACHE_MUTATION_DETECTOR"
  1209. kube_cache_mutation_detector_env_value="value: \"${ENABLE_CACHE_MUTATION_DETECTOR}\""
  1210. fi
  1211. sed -i -e "s@{{kubeconfig}}@${kubeconfig}@g" ${src_file}
  1212. sed -i -e "s@{{pillar\['kube_docker_registry'\]}}@${kube_docker_registry}@g" ${src_file}
  1213. sed -i -e "s@{{pillar\['kube-proxy_docker_tag'\]}}@${kube_proxy_docker_tag}@g" ${src_file}
  1214. sed -i -e "s@{{params}}@${params}@g" ${src_file}
  1215. sed -i -e "s@{{container_env}}@${container_env}@g" ${src_file}
  1216. sed -i -e "s@{{kube_cache_mutation_detector_env_name}}@${kube_cache_mutation_detector_env_name}@g" ${src_file}
  1217. sed -i -e "s@{{kube_cache_mutation_detector_env_value}}@${kube_cache_mutation_detector_env_value}@g" ${src_file}
  1218. sed -i -e "s@{{ cpurequest }}@100m@g" ${src_file}
  1219. sed -i -e "s@{{api_servers_with_port}}@${api_servers}@g" ${src_file}
  1220. sed -i -e "s@{{kubernetes_service_host_env_value}}@${KUBERNETES_MASTER_NAME}@g" ${src_file}
  1221. if [[ -n "${CLUSTER_IP_RANGE:-}" ]]; then
  1222. sed -i -e "s@{{cluster_cidr}}@--cluster-cidr=${CLUSTER_IP_RANGE}@g" ${src_file}
  1223. fi
  1224. }
  1225. # Starts kube-proxy static pod.
  1226. function start-kube-proxy {
  1227. echo "Start kube-proxy static pod"
  1228. prepare-log-file /var/log/kube-proxy.log
  1229. local -r src_file="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/kube-proxy.manifest"
  1230. prepare-kube-proxy-manifest-variables "${src_file}"
  1231. cp "${src_file}" /etc/kubernetes/manifests
  1232. }
  1233. # Replaces the variables in the etcd manifest file with the real values, and then
  1234. # copy the file to the manifest dir
  1235. # $1: value for variable 'suffix'
  1236. # $2: value for variable 'port'
  1237. # $3: value for variable 'server_port'
  1238. # $4: value for variable 'cpulimit'
  1239. # $5: pod name, which should be either etcd or etcd-events
  1240. function prepare-etcd-manifest {
  1241. local host_name=${ETCD_HOSTNAME:-$(hostname -s)}
  1242. local host_ip=$(python -c "import socket;print(socket.gethostbyname(\"${host_name}\"))")
  1243. local etcd_cluster=""
  1244. local cluster_state="new"
  1245. local etcd_protocol="http"
  1246. local etcd_creds=""
  1247. local etcd_apiserver_creds="${ETCD_APISERVER_CREDS:-}"
  1248. local etcd_extra_args="${ETCD_EXTRA_ARGS:-}"
  1249. if [[ -n "${INITIAL_ETCD_CLUSTER_STATE:-}" ]]; then
  1250. cluster_state="${INITIAL_ETCD_CLUSTER_STATE}"
  1251. fi
  1252. if [[ -n "${ETCD_CA_KEY:-}" && -n "${ETCD_CA_CERT:-}" && -n "${ETCD_PEER_KEY:-}" && -n "${ETCD_PEER_CERT:-}" ]]; then
  1253. etcd_creds=" --peer-trusted-ca-file /etc/srv/kubernetes/etcd-ca.crt --peer-cert-file /etc/srv/kubernetes/etcd-peer.crt --peer-key-file /etc/srv/kubernetes/etcd-peer.key -peer-client-cert-auth "
  1254. etcd_protocol="https"
  1255. fi
  1256. if [[ -n "${ETCD_APISERVER_CA_KEY:-}" && -n "${ETCD_APISERVER_CA_CERT:-}" && -n "${ETCD_APISERVER_SERVER_KEY:-}" && -n "${ETCD_APISERVER_SERVER_CERT:-}" ]]; then
  1257. etcd_apiserver_creds=" --client-cert-auth --trusted-ca-file ${ETCD_APISERVER_CA_CERT_PATH} --cert-file ${ETCD_APISERVER_SERVER_CERT_PATH} --key-file ${ETCD_APISERVER_SERVER_KEY_PATH} "
  1258. fi
  1259. for host in $(echo "${INITIAL_ETCD_CLUSTER:-${host_name}}" | tr "," "\n"); do
  1260. etcd_host="etcd-${host}=${etcd_protocol}://${host}:$3"
  1261. if [[ -n "${etcd_cluster}" ]]; then
  1262. etcd_cluster+=","
  1263. fi
  1264. etcd_cluster+="${etcd_host}"
  1265. done
  1266. local -r temp_file="/tmp/$5"
  1267. cp "${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/etcd.manifest" "${temp_file}"
  1268. sed -i -e "s@{{ *suffix *}}@$1@g" "${temp_file}"
  1269. sed -i -e "s@{{ *port *}}@$2@g" "${temp_file}"
  1270. sed -i -e "s@{{ *server_port *}}@$3@g" "${temp_file}"
  1271. sed -i -e "s@{{ *cpulimit *}}@\"$4\"@g" "${temp_file}"
  1272. sed -i -e "s@{{ *hostname *}}@$host_name@g" "${temp_file}"
  1273. sed -i -e "s@{{ *host_ip *}}@$host_ip@g" "${temp_file}"
  1274. sed -i -e "s@{{ *etcd_cluster *}}@$etcd_cluster@g" "${temp_file}"
  1275. sed -i -e "s@{{ *liveness_probe_initial_delay *}}@${ETCD_LIVENESS_PROBE_INITIAL_DELAY_SEC:-15}@g" "${temp_file}"
  1276. sed -i -e "s@{{ *listen_client_ip *}}@${ETCD_LISTEN_CLIENT_IP:-127.0.0.1}@g" "${temp_file}"
  1277. # Get default storage backend from manifest file.
  1278. local -r default_storage_backend=$(cat "${temp_file}" | \
  1279. grep -o "{{ *pillar\.get('storage_backend', '\(.*\)') *}}" | \
  1280. sed -e "s@{{ *pillar\.get('storage_backend', '\(.*\)') *}}@\1@g")
  1281. if [[ -n "${STORAGE_BACKEND:-}" ]]; then
  1282. sed -i -e "s@{{ *pillar\.get('storage_backend', '\(.*\)') *}}@${STORAGE_BACKEND}@g" "${temp_file}"
  1283. else
  1284. sed -i -e "s@{{ *pillar\.get('storage_backend', '\(.*\)') *}}@\1@g" "${temp_file}"
  1285. fi
  1286. if [[ "${STORAGE_BACKEND:-${default_storage_backend}}" == "etcd3" ]]; then
  1287. sed -i -e "s@{{ *quota_bytes *}}@--quota-backend-bytes=${ETCD_QUOTA_BACKEND_BYTES:-4294967296}@g" "${temp_file}"
  1288. else
  1289. sed -i -e "s@{{ *quota_bytes *}}@@g" "${temp_file}"
  1290. fi
  1291. sed -i -e "s@{{ *cluster_state *}}@$cluster_state@g" "${temp_file}"
  1292. if [[ -n "${ETCD_IMAGE:-}" ]]; then
  1293. sed -i -e "s@{{ *pillar\.get('etcd_docker_tag', '\(.*\)') *}}@${ETCD_IMAGE}@g" "${temp_file}"
  1294. else
  1295. sed -i -e "s@{{ *pillar\.get('etcd_docker_tag', '\(.*\)') *}}@\1@g" "${temp_file}"
  1296. fi
  1297. if [[ -n "${ETCD_DOCKER_REPOSITORY:-}" ]]; then
  1298. sed -i -e "s@{{ *pillar\.get('etcd_docker_repository', '\(.*\)') *}}@${ETCD_DOCKER_REPOSITORY}@g" "${temp_file}"
  1299. else
  1300. sed -i -e "s@{{ *pillar\.get('etcd_docker_repository', '\(.*\)') *}}@\1@g" "${temp_file}"
  1301. fi
  1302. sed -i -e "s@{{ *etcd_protocol *}}@$etcd_protocol@g" "${temp_file}"
  1303. sed -i -e "s@{{ *etcd_creds *}}@$etcd_creds@g" "${temp_file}"
  1304. sed -i -e "s@{{ *etcd_apiserver_creds *}}@$etcd_apiserver_creds@g" "${temp_file}"
  1305. sed -i -e "s@{{ *etcd_extra_args *}}@$etcd_extra_args@g" "${temp_file}"
  1306. if [[ -n "${ETCD_VERSION:-}" ]]; then
  1307. sed -i -e "s@{{ *pillar\.get('etcd_version', '\(.*\)') *}}@${ETCD_VERSION}@g" "${temp_file}"
  1308. else
  1309. sed -i -e "s@{{ *pillar\.get('etcd_version', '\(.*\)') *}}@\1@g" "${temp_file}"
  1310. fi
  1311. # Replace the volume host path.
  1312. sed -i -e "s@/mnt/master-pd/var/etcd@/mnt/disks/master-pd/var/etcd@g" "${temp_file}"
  1313. mv "${temp_file}" /etc/kubernetes/manifests
  1314. }
  1315. function start-etcd-empty-dir-cleanup-pod {
  1316. local -r src_file="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/etcd-empty-dir-cleanup.yaml"
  1317. cp "${src_file}" "/etc/kubernetes/manifests"
  1318. }
  1319. # Starts etcd server pod (and etcd-events pod if needed).
  1320. # More specifically, it prepares dirs and files, sets the variable value
  1321. # in the manifests, and copies them to /etc/kubernetes/manifests.
  1322. function start-etcd-servers {
  1323. echo "Start etcd pods"
  1324. if [[ -d /etc/etcd ]]; then
  1325. rm -rf /etc/etcd
  1326. fi
  1327. if [[ -e /etc/default/etcd ]]; then
  1328. rm -f /etc/default/etcd
  1329. fi
  1330. if [[ -e /etc/systemd/system/etcd.service ]]; then
  1331. rm -f /etc/systemd/system/etcd.service
  1332. fi
  1333. if [[ -e /etc/init.d/etcd ]]; then
  1334. rm -f /etc/init.d/etcd
  1335. fi
  1336. prepare-log-file /var/log/etcd.log
  1337. prepare-etcd-manifest "" "2379" "2380" "200m" "etcd.manifest"
  1338. prepare-log-file /var/log/etcd-events.log
  1339. prepare-etcd-manifest "-events" "4002" "2381" "100m" "etcd-events.manifest"
  1340. }
  1341. # Calculates the following variables based on env variables, which will be used
  1342. # by the manifests of several kube-master components.
  1343. # CLOUD_CONFIG_OPT
  1344. # CLOUD_CONFIG_VOLUME
  1345. # CLOUD_CONFIG_MOUNT
  1346. # DOCKER_REGISTRY
  1347. # FLEXVOLUME_HOSTPATH_MOUNT
  1348. # FLEXVOLUME_HOSTPATH_VOLUME
  1349. # INSECURE_PORT_MAPPING
  1350. function compute-master-manifest-variables {
  1351. CLOUD_CONFIG_OPT=""
  1352. CLOUD_CONFIG_VOLUME=""
  1353. CLOUD_CONFIG_MOUNT=""
  1354. if [[ -f /etc/gce.conf ]]; then
  1355. CLOUD_CONFIG_OPT="--cloud-config=/etc/gce.conf"
  1356. CLOUD_CONFIG_VOLUME="{\"name\": \"cloudconfigmount\",\"hostPath\": {\"path\": \"/etc/gce.conf\", \"type\": \"FileOrCreate\"}},"
  1357. CLOUD_CONFIG_MOUNT="{\"name\": \"cloudconfigmount\",\"mountPath\": \"/etc/gce.conf\", \"readOnly\": true},"
  1358. fi
  1359. DOCKER_REGISTRY="k8s.gcr.io"
  1360. if [[ -n "${KUBE_DOCKER_REGISTRY:-}" ]]; then
  1361. DOCKER_REGISTRY="${KUBE_DOCKER_REGISTRY}"
  1362. fi
  1363. FLEXVOLUME_HOSTPATH_MOUNT=""
  1364. FLEXVOLUME_HOSTPATH_VOLUME=""
  1365. if [[ -n "${VOLUME_PLUGIN_DIR:-}" ]]; then
  1366. FLEXVOLUME_HOSTPATH_MOUNT="{ \"name\": \"flexvolumedir\", \"mountPath\": \"${VOLUME_PLUGIN_DIR}\", \"readOnly\": true},"
  1367. FLEXVOLUME_HOSTPATH_VOLUME="{ \"name\": \"flexvolumedir\", \"hostPath\": {\"path\": \"${VOLUME_PLUGIN_DIR}\"}},"
  1368. fi
  1369. INSECURE_PORT_MAPPING=""
  1370. if [[ "${ENABLE_APISERVER_INSECURE_PORT:-false}" == "true" ]]; then
  1371. INSECURE_PORT_MAPPING="{ \"name\": \"local\", \"containerPort\": 8080, \"hostPort\": 8080},"
  1372. fi
  1373. }
  1374. # A helper function that bind mounts kubelet dirs for running mount in a chroot
  1375. function prepare-mounter-rootfs {
  1376. echo "Prepare containerized mounter"
  1377. mount --bind "${CONTAINERIZED_MOUNTER_HOME}" "${CONTAINERIZED_MOUNTER_HOME}"
  1378. mount -o remount,exec "${CONTAINERIZED_MOUNTER_HOME}"
  1379. CONTAINERIZED_MOUNTER_ROOTFS="${CONTAINERIZED_MOUNTER_HOME}/rootfs"
  1380. mount --rbind /var/lib/kubelet/ "${CONTAINERIZED_MOUNTER_ROOTFS}/var/lib/kubelet"
  1381. mount --make-rshared "${CONTAINERIZED_MOUNTER_ROOTFS}/var/lib/kubelet"
  1382. mount --bind -o ro /proc "${CONTAINERIZED_MOUNTER_ROOTFS}/proc"
  1383. mount --bind -o ro /dev "${CONTAINERIZED_MOUNTER_ROOTFS}/dev"
  1384. cp /etc/resolv.conf "${CONTAINERIZED_MOUNTER_ROOTFS}/etc/"
  1385. }
  1386. # Starts kubernetes apiserver.
  1387. # It prepares the log file, loads the docker image, calculates variables, sets them
  1388. # in the manifest file, and then copies the manifest file to /etc/kubernetes/manifests.
  1389. #
  1390. # Assumed vars (which are calculated in function compute-master-manifest-variables)
  1391. # CLOUD_CONFIG_OPT
  1392. # CLOUD_CONFIG_VOLUME
  1393. # CLOUD_CONFIG_MOUNT
  1394. # DOCKER_REGISTRY
  1395. # INSECURE_PORT_MAPPING
  1396. function start-kube-apiserver {
  1397. echo "Start kubernetes api-server"
  1398. prepare-log-file "${KUBE_API_SERVER_LOG_PATH:-/var/log/kube-apiserver.log}"
  1399. prepare-log-file "${KUBE_API_SERVER_AUDIT_LOG_PATH:-/var/log/kube-apiserver-audit.log}"
  1400. # Calculate variables and assemble the command line.
  1401. local params="${API_SERVER_TEST_LOG_LEVEL:-"--v=2"} ${APISERVER_TEST_ARGS:-} ${CLOUD_CONFIG_OPT}"
  1402. params+=" --address=127.0.0.1"
  1403. params+=" --allow-privileged=true"
  1404. params+=" --cloud-provider=gce"
  1405. params+=" --client-ca-file=${CA_CERT_BUNDLE_PATH}"
  1406. params+=" --etcd-servers=${ETCD_SERVERS:-http://127.0.0.1:2379}"
  1407. if [[ -z "${ETCD_SERVERS:-}" ]]; then
  1408. params+=" --etcd-servers-overrides=${ETCD_SERVERS_OVERRIDES:-/events#http://127.0.0.1:4002}"
  1409. elif [[ -n "${ETCD_SERVERS_OVERRIDES:-}" ]]; then
  1410. params+=" --etcd-servers-overrides=${ETCD_SERVERS_OVERRIDES:-}"
  1411. fi
  1412. if [[ -n "${ETCD_APISERVER_CA_KEY:-}" && -n "${ETCD_APISERVER_CA_CERT:-}" && -n "${ETCD_APISERVER_CLIENT_KEY:-}" && -n "${ETCD_APISERVER_CLIENT_CERT:-}" ]]; then
  1413. params+=" --etcd-cafile=${ETCD_APISERVER_CA_CERT_PATH}"
  1414. params+=" --etcd-certfile=${ETCD_APISERVER_CLIENT_CERT_PATH}"
  1415. params+=" --etcd-keyfile=${ETCD_APISERVER_CLIENT_KEY_PATH}"
  1416. fi
  1417. params+=" --secure-port=443"
  1418. if [[ "${ENABLE_APISERVER_INSECURE_PORT:-false}" != "true" ]]; then
  1419. # Default is :8080
  1420. params+=" --insecure-port=0"
  1421. fi
  1422. params+=" --tls-cert-file=${APISERVER_SERVER_CERT_PATH}"
  1423. params+=" --tls-private-key-file=${APISERVER_SERVER_KEY_PATH}"
  1424. params+=" --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname"
  1425. if [[ -s "${REQUESTHEADER_CA_CERT_PATH:-}" ]]; then
  1426. params+=" --requestheader-client-ca-file=${REQUESTHEADER_CA_CERT_PATH}"
  1427. params+=" --requestheader-allowed-names=aggregator"
  1428. params+=" --requestheader-extra-headers-prefix=X-Remote-Extra-"
  1429. params+=" --requestheader-group-headers=X-Remote-Group"
  1430. params+=" --requestheader-username-headers=X-Remote-User"
  1431. params+=" --proxy-client-cert-file=${PROXY_CLIENT_CERT_PATH}"
  1432. params+=" --proxy-client-key-file=${PROXY_CLIENT_KEY_PATH}"
  1433. fi
  1434. params+=" --enable-aggregator-routing=true"
  1435. if [[ -e "${APISERVER_CLIENT_CERT_PATH}" ]] && [[ -e "${APISERVER_CLIENT_KEY_PATH}" ]]; then
  1436. params+=" --kubelet-client-certificate=${APISERVER_CLIENT_CERT_PATH}"
  1437. params+=" --kubelet-client-key=${APISERVER_CLIENT_KEY_PATH}"
  1438. fi
  1439. if [[ -n "${SERVICEACCOUNT_CERT_PATH:-}" ]]; then
  1440. params+=" --service-account-key-file=${SERVICEACCOUNT_CERT_PATH}"
  1441. fi
  1442. params+=" --token-auth-file=/etc/srv/kubernetes/known_tokens.csv"
  1443. if [[ -n "${KUBE_PASSWORD:-}" && -n "${KUBE_USER:-}" ]]; then
  1444. params+=" --basic-auth-file=/etc/srv/kubernetes/basic_auth.csv"
  1445. fi
  1446. if [[ -n "${STORAGE_BACKEND:-}" ]]; then
  1447. params+=" --storage-backend=${STORAGE_BACKEND}"
  1448. fi
  1449. if [[ -n "${STORAGE_MEDIA_TYPE:-}" ]]; then
  1450. params+=" --storage-media-type=${STORAGE_MEDIA_TYPE}"
  1451. fi
  1452. if [[ -n "${ETCD_COMPACTION_INTERVAL_SEC:-}" ]]; then
  1453. params+=" --etcd-compaction-interval=${ETCD_COMPACTION_INTERVAL_SEC}s"
  1454. fi
  1455. if [[ -n "${KUBE_APISERVER_REQUEST_TIMEOUT_SEC:-}" ]]; then
  1456. params+=" --request-timeout=${KUBE_APISERVER_REQUEST_TIMEOUT_SEC}s"
  1457. fi
  1458. if [[ -n "${ENABLE_GARBAGE_COLLECTOR:-}" ]]; then
  1459. params+=" --enable-garbage-collector=${ENABLE_GARBAGE_COLLECTOR}"
  1460. fi
  1461. if [[ -n "${NUM_NODES:-}" ]]; then
  1462. # If the cluster is large, increase max-requests-inflight limit in apiserver.
  1463. if [[ "${NUM_NODES}" -gt 3000 ]]; then
  1464. params+=" --max-requests-inflight=3000 --max-mutating-requests-inflight=1000"
  1465. elif [[ "${NUM_NODES}" -gt 500 ]]; then
  1466. params+=" --max-requests-inflight=1500 --max-mutating-requests-inflight=500"
  1467. fi
  1468. # Set amount of memory available for apiserver based on number of nodes.
  1469. # TODO: Once we start setting proper requests and limits for apiserver
  1470. # we should reuse the same logic here instead of current heuristic.
  1471. params+=" --target-ram-mb=$((${NUM_NODES} * 60))"
  1472. fi
  1473. if [[ -n "${SERVICE_CLUSTER_IP_RANGE:-}" ]]; then
  1474. params+=" --service-cluster-ip-range=${SERVICE_CLUSTER_IP_RANGE}"
  1475. fi
  1476. params+=" --service-account-issuer=${SERVICEACCOUNT_ISSUER}"
  1477. params+=" --service-account-api-audiences=${SERVICEACCOUNT_ISSUER}"
  1478. params+=" --service-account-signing-key-file=${SERVICEACCOUNT_KEY_PATH}"
  1479. local audit_policy_config_mount=""
  1480. local audit_policy_config_volume=""
  1481. local audit_webhook_config_mount=""
  1482. local audit_webhook_config_volume=""
  1483. if [[ "${ENABLE_APISERVER_ADVANCED_AUDIT:-}" == "true" ]]; then
  1484. local -r audit_policy_file="/etc/audit_policy.config"
  1485. params+=" --audit-policy-file=${audit_policy_file}"
  1486. # Create the audit policy file, and mount it into the apiserver pod.
  1487. create-master-audit-policy "${audit_policy_file}" "${ADVANCED_AUDIT_POLICY:-}"
  1488. audit_policy_config_mount="{\"name\": \"auditpolicyconfigmount\",\"mountPath\": \"${audit_policy_file}\", \"readOnly\": true},"
  1489. audit_policy_config_volume="{\"name\": \"auditpolicyconfigmount\",\"hostPath\": {\"path\": \"${audit_policy_file}\", \"type\": \"FileOrCreate\"}},"
  1490. if [[ "${ADVANCED_AUDIT_BACKEND:-log}" == *"log"* ]]; then
  1491. # The advanced audit log backend config matches the basic audit log config.
  1492. params+=" --audit-log-path=/var/log/kube-apiserver-audit.log"
  1493. params+=" --audit-log-maxage=0"
  1494. params+=" --audit-log-maxbackup=0"
  1495. # Lumberjack doesn't offer any way to disable size-based rotation. It also
  1496. # has an in-memory counter that doesn't notice if you truncate the file.
  1497. # 2000000000 (in MiB) is a large number that fits in 31 bits. If the log
  1498. # grows at 10MiB/s (~30K QPS), it will rotate after ~6 years if apiserver
  1499. # never restarts. Please manually restart apiserver before this time.
  1500. params+=" --audit-log-maxsize=2000000000"
  1501. # Batching parameters
  1502. if [[ -n "${ADVANCED_AUDIT_LOG_MODE:-}" ]]; then
  1503. params+=" --audit-log-mode=${ADVANCED_AUDIT_LOG_MODE}"
  1504. fi
  1505. if [[ -n "${ADVANCED_AUDIT_LOG_BUFFER_SIZE:-}" ]]; then
  1506. params+=" --audit-log-batch-buffer-size=${ADVANCED_AUDIT_LOG_BUFFER_SIZE}"
  1507. fi
  1508. if [[ -n "${ADVANCED_AUDIT_LOG_MAX_BATCH_SIZE:-}" ]]; then
  1509. params+=" --audit-log-batch-max-size=${ADVANCED_AUDIT_LOG_MAX_BATCH_SIZE}"
  1510. fi
  1511. if [[ -n "${ADVANCED_AUDIT_LOG_MAX_BATCH_WAIT:-}" ]]; then
  1512. params+=" --audit-log-batch-max-wait=${ADVANCED_AUDIT_LOG_MAX_BATCH_WAIT}"
  1513. fi
  1514. if [[ -n "${ADVANCED_AUDIT_LOG_THROTTLE_QPS:-}" ]]; then
  1515. params+=" --audit-log-batch-throttle-qps=${ADVANCED_AUDIT_LOG_THROTTLE_QPS}"
  1516. fi
  1517. if [[ -n "${ADVANCED_AUDIT_LOG_THROTTLE_BURST:-}" ]]; then
  1518. params+=" --audit-log-batch-throttle-burst=${ADVANCED_AUDIT_LOG_THROTTLE_BURST}"
  1519. fi
  1520. if [[ -n "${ADVANCED_AUDIT_LOG_INITIAL_BACKOFF:-}" ]]; then
  1521. params+=" --audit-log-initial-backoff=${ADVANCED_AUDIT_LOG_INITIAL_BACKOFF}"
  1522. fi
  1523. # Truncating backend parameters
  1524. if [[ -n "${ADVANCED_AUDIT_TRUNCATING_BACKEND:-}" ]]; then
  1525. params+=" --audit-log-truncate-enabled=${ADVANCED_AUDIT_TRUNCATING_BACKEND}"
  1526. fi
  1527. fi
  1528. if [[ "${ADVANCED_AUDIT_BACKEND:-}" == *"webhook"* ]]; then
  1529. # Create the audit webhook config file, and mount it into the apiserver pod.
  1530. local -r audit_webhook_config_file="/etc/audit_webhook.config"
  1531. params+=" --audit-webhook-config-file=${audit_webhook_config_file}"
  1532. create-master-audit-webhook-config "${audit_webhook_config_file}"
  1533. audit_webhook_config_mount="{\"name\": \"auditwebhookconfigmount\",\"mountPath\": \"${audit_webhook_config_file}\", \"readOnly\": true},"
  1534. audit_webhook_config_volume="{\"name\": \"auditwebhookconfigmount\",\"hostPath\": {\"path\": \"${audit_webhook_config_file}\", \"type\": \"FileOrCreate\"}},"
  1535. # Batching parameters
  1536. if [[ -n "${ADVANCED_AUDIT_WEBHOOK_MODE:-}" ]]; then
  1537. params+=" --audit-webhook-mode=${ADVANCED_AUDIT_WEBHOOK_MODE}"
  1538. else
  1539. params+=" --audit-webhook-mode=batch"
  1540. fi
  1541. if [[ -n "${ADVANCED_AUDIT_WEBHOOK_BUFFER_SIZE:-}" ]]; then
  1542. params+=" --audit-webhook-batch-buffer-size=${ADVANCED_AUDIT_WEBHOOK_BUFFER_SIZE}"
  1543. fi
  1544. if [[ -n "${ADVANCED_AUDIT_WEBHOOK_MAX_BATCH_SIZE:-}" ]]; then
  1545. params+=" --audit-webhook-batch-max-size=${ADVANCED_AUDIT_WEBHOOK_MAX_BATCH_SIZE}"
  1546. fi
  1547. if [[ -n "${ADVANCED_AUDIT_WEBHOOK_MAX_BATCH_WAIT:-}" ]]; then
  1548. params+=" --audit-webhook-batch-max-wait=${ADVANCED_AUDIT_WEBHOOK_MAX_BATCH_WAIT}"
  1549. fi
  1550. if [[ -n "${ADVANCED_AUDIT_WEBHOOK_THROTTLE_QPS:-}" ]]; then
  1551. params+=" --audit-webhook-batch-throttle-qps=${ADVANCED_AUDIT_WEBHOOK_THROTTLE_QPS}"
  1552. fi
  1553. if [[ -n "${ADVANCED_AUDIT_WEBHOOK_THROTTLE_BURST:-}" ]]; then
  1554. params+=" --audit-webhook-batch-throttle-burst=${ADVANCED_AUDIT_WEBHOOK_THROTTLE_BURST}"
  1555. fi
  1556. if [[ -n "${ADVANCED_AUDIT_WEBHOOK_INITIAL_BACKOFF:-}" ]]; then
  1557. params+=" --audit-webhook-initial-backoff=${ADVANCED_AUDIT_WEBHOOK_INITIAL_BACKOFF}"
  1558. fi
  1559. # Truncating backend parameters
  1560. if [[ -n "${ADVANCED_AUDIT_TRUNCATING_BACKEND:-}" ]]; then
  1561. params+=" --audit-webhook-truncate-enabled=${ADVANCED_AUDIT_TRUNCATING_BACKEND}"
  1562. fi
  1563. fi
  1564. fi
  1565. if [[ "${ENABLE_APISERVER_DYNAMIC_AUDIT:-}" == "true" ]]; then
  1566. params+=" --audit-dynamic-configuration"
  1567. RUNTIME_CONFIG="${RUNTIME_CONFIG},auditconfiguration.k8s.io/v1alpha1=true"
  1568. fi
  1569. if [[ "${ENABLE_APISERVER_LOGS_HANDLER:-}" == "false" ]]; then
  1570. params+=" --enable-logs-handler=false"
  1571. fi
  1572. if [[ "${APISERVER_SET_KUBELET_CA:-false}" == "true" ]]; then
  1573. params+=" --kubelet-certificate-authority=${CA_CERT_BUNDLE_PATH}"
  1574. fi
  1575. local admission_controller_config_mount=""
  1576. local admission_controller_config_volume=""
  1577. local image_policy_webhook_config_mount=""
  1578. local image_policy_webhook_config_volume=""
  1579. if [[ -n "${ADMISSION_CONTROL:-}" ]]; then
  1580. params+=" --admission-control=${ADMISSION_CONTROL}"
  1581. if [[ ${ADMISSION_CONTROL} == *"ImagePolicyWebhook"* ]]; then
  1582. params+=" --admission-control-config-file=/etc/admission_controller.config"
  1583. # Mount the file to configure admission controllers if ImagePolicyWebhook is set.
  1584. admission_controller_config_mount="{\"name\": \"admissioncontrollerconfigmount\",\"mountPath\": \"/etc/admission_controller.config\", \"readOnly\": false},"
  1585. admission_controller_config_volume="{\"name\": \"admissioncontrollerconfigmount\",\"hostPath\": {\"path\": \"/etc/admission_controller.config\", \"type\": \"FileOrCreate\"}},"
  1586. # Mount the file to configure the ImagePolicyWebhook's webhook.
  1587. image_policy_webhook_config_mount="{\"name\": \"imagepolicywebhookconfigmount\",\"mountPath\": \"/etc/gcp_image_review.config\", \"readOnly\": false},"
  1588. image_policy_webhook_config_volume="{\"name\": \"imagepolicywebhookconfigmount\",\"hostPath\": {\"path\": \"/etc/gcp_image_review.config\", \"type\": \"FileOrCreate\"}},"
  1589. fi
  1590. fi
  1591. if [[ -n "${KUBE_APISERVER_REQUEST_TIMEOUT:-}" ]]; then
  1592. params+=" --min-request-timeout=${KUBE_APISERVER_REQUEST_TIMEOUT}"
  1593. fi
  1594. if [[ -n "${RUNTIME_CONFIG:-}" ]]; then
  1595. params+=" --runtime-config=${RUNTIME_CONFIG}"
  1596. fi
  1597. if [[ -n "${FEATURE_GATES:-}" ]]; then
  1598. params+=" --feature-gates=${FEATURE_GATES}"
  1599. fi
  1600. if [[ "${FEATURE_GATES:-}" =~ "RuntimeClass=true" ]]; then
  1601. params+=" --runtime-config=node.k8s.io/v1alpha1=true"
  1602. fi
  1603. if [[ -n "${MASTER_ADVERTISE_ADDRESS:-}" ]]; then
  1604. params+=" --advertise-address=${MASTER_ADVERTISE_ADDRESS}"
  1605. if [[ -n "${PROXY_SSH_USER:-}" ]]; then
  1606. params+=" --ssh-user=${PROXY_SSH_USER}"
  1607. params+=" --ssh-keyfile=/etc/srv/sshproxy/.sshkeyfile"
  1608. fi
  1609. elif [[ -n "${PROJECT_ID:-}" && -n "${TOKEN_URL:-}" && -n "${TOKEN_BODY:-}" && -n "${NODE_NETWORK:-}" ]]; then
  1610. local -r vm_external_ip=$(get-metadata-value "instance/network-interfaces/0/access-configs/0/external-ip")
  1611. if [[ -n "${PROXY_SSH_USER:-}" ]]; then
  1612. params+=" --advertise-address=${vm_external_ip}"
  1613. params+=" --ssh-user=${PROXY_SSH_USER}"
  1614. params+=" --ssh-keyfile=/etc/srv/sshproxy/.sshkeyfile"
  1615. fi
  1616. fi
  1617. local webhook_authn_config_mount=""
  1618. local webhook_authn_config_volume=""
  1619. if [[ -n "${GCP_AUTHN_URL:-}" ]]; then
  1620. params+=" --authentication-token-webhook-config-file=/etc/gcp_authn.config"
  1621. webhook_authn_config_mount="{\"name\": \"webhookauthnconfigmount\",\"mountPath\": \"/etc/gcp_authn.config\", \"readOnly\": false},"
  1622. webhook_authn_config_volume="{\"name\": \"webhookauthnconfigmount\",\"hostPath\": {\"path\": \"/etc/gcp_authn.config\", \"type\": \"FileOrCreate\"}},"
  1623. if [[ -n "${GCP_AUTHN_CACHE_TTL:-}" ]]; then
  1624. params+=" --authentication-token-webhook-cache-ttl=${GCP_AUTHN_CACHE_TTL}"
  1625. fi
  1626. fi
  1627. local authorization_mode="RBAC"
  1628. local -r src_dir="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty"
  1629. # Enable ABAC mode unless the user explicitly opts out with ENABLE_LEGACY_ABAC=false
  1630. if [[ "${ENABLE_LEGACY_ABAC:-}" != "false" ]]; then
  1631. echo "Warning: Enabling legacy ABAC policy. All service accounts will have superuser API access. Set ENABLE_LEGACY_ABAC=false to disable this."
  1632. # Create the ABAC file if it doesn't exist yet, or if we have a KUBE_USER set (to ensure the right user is given permissions)
  1633. if [[ -n "${KUBE_USER:-}" || ! -e /etc/srv/kubernetes/abac-authz-policy.jsonl ]]; then
  1634. local -r abac_policy_json="${src_dir}/abac-authz-policy.jsonl"
  1635. if [[ -n "${KUBE_USER:-}" ]]; then
  1636. sed -i -e "s/{{kube_user}}/${KUBE_USER}/g" "${abac_policy_json}"
  1637. else
  1638. sed -i -e "/{{kube_user}}/d" "${abac_policy_json}"
  1639. fi
  1640. cp "${abac_policy_json}" /etc/srv/kubernetes/
  1641. fi
  1642. params+=" --authorization-policy-file=/etc/srv/kubernetes/abac-authz-policy.jsonl"
  1643. authorization_mode+=",ABAC"
  1644. fi
  1645. local webhook_config_mount=""
  1646. local webhook_config_volume=""
  1647. if [[ -n "${GCP_AUTHZ_URL:-}" ]]; then
  1648. authorization_mode="${authorization_mode},Webhook"
  1649. params+=" --authorization-webhook-config-file=/etc/gcp_authz.config"
  1650. webhook_config_mount="{\"name\": \"webhookconfigmount\",\"mountPath\": \"/etc/gcp_authz.config\", \"readOnly\": false},"
  1651. webhook_config_volume="{\"name\": \"webhookconfigmount\",\"hostPath\": {\"path\": \"/etc/gcp_authz.config\", \"type\": \"FileOrCreate\"}},"
  1652. if [[ -n "${GCP_AUTHZ_CACHE_AUTHORIZED_TTL:-}" ]]; then
  1653. params+=" --authorization-webhook-cache-authorized-ttl=${GCP_AUTHZ_CACHE_AUTHORIZED_TTL}"
  1654. fi
  1655. if [[ -n "${GCP_AUTHZ_CACHE_UNAUTHORIZED_TTL:-}" ]]; then
  1656. params+=" --authorization-webhook-cache-unauthorized-ttl=${GCP_AUTHZ_CACHE_UNAUTHORIZED_TTL}"
  1657. fi
  1658. fi
  1659. authorization_mode="Node,${authorization_mode}"
  1660. params+=" --authorization-mode=${authorization_mode}"
  1661. local container_env=""
  1662. if [[ -n "${ENABLE_CACHE_MUTATION_DETECTOR:-}" ]]; then
  1663. container_env+="{\"name\": \"KUBE_CACHE_MUTATION_DETECTOR\", \"value\": \"${ENABLE_CACHE_MUTATION_DETECTOR}\"}"
  1664. fi
  1665. if [[ -n "${ENABLE_PATCH_CONVERSION_DETECTOR:-}" ]]; then
  1666. if [[ -n "${container_env}" ]]; then
  1667. container_env="${container_env}, "
  1668. fi
  1669. container_env+="{\"name\": \"KUBE_PATCH_CONVERSION_DETECTOR\", \"value\": \"${ENABLE_PATCH_CONVERSION_DETECTOR}\"}"
  1670. fi
  1671. if [[ -n "${container_env}" ]]; then
  1672. container_env="\"env\":[${container_env}],"
  1673. fi
  1674. local -r src_file="${src_dir}/kube-apiserver.manifest"
  1675. # params is passed by reference, so no "$"
  1676. setup-etcd-encryption "${src_file}" params
  1677. # Evaluate variables.
  1678. local -r kube_apiserver_docker_tag="${KUBE_API_SERVER_DOCKER_TAG:-$(cat /home/kubernetes/kube-docker-files/kube-apiserver.docker_tag)}"
  1679. sed -i -e "s@{{params}}@${params}@g" "${src_file}"
  1680. sed -i -e "s@{{container_env}}@${container_env}@g" ${src_file}
  1681. sed -i -e "s@{{srv_sshproxy_path}}@/etc/srv/sshproxy@g" "${src_file}"
  1682. sed -i -e "s@{{cloud_config_mount}}@${CLOUD_CONFIG_MOUNT}@g" "${src_file}"
  1683. sed -i -e "s@{{cloud_config_volume}}@${CLOUD_CONFIG_VOLUME}@g" "${src_file}"
  1684. sed -i -e "s@{{pillar\['kube_docker_registry'\]}}@${DOCKER_REGISTRY}@g" "${src_file}"
  1685. sed -i -e "s@{{pillar\['kube-apiserver_docker_tag'\]}}@${kube_apiserver_docker_tag}@g" "${src_file}"
  1686. sed -i -e "s@{{pillar\['allow_privileged'\]}}@true@g" "${src_file}"
  1687. sed -i -e "s@{{liveness_probe_initial_delay}}@${KUBE_APISERVER_LIVENESS_PROBE_INITIAL_DELAY_SEC:-15}@g" "${src_file}"
  1688. sed -i -e "s@{{secure_port}}@443@g" "${src_file}"
  1689. sed -i -e "s@{{insecure_port_mapping}}@${INSECURE_PORT_MAPPING}@g" "${src_file}"
  1690. sed -i -e "s@{{additional_cloud_config_mount}}@@g" "${src_file}"
  1691. sed -i -e "s@{{additional_cloud_config_volume}}@@g" "${src_file}"
  1692. sed -i -e "s@{{webhook_authn_config_mount}}@${webhook_authn_config_mount}@g" "${src_file}"
  1693. sed -i -e "s@{{webhook_authn_config_volume}}@${webhook_authn_config_volume}@g" "${src_file}"
  1694. sed -i -e "s@{{webhook_config_mount}}@${webhook_config_mount}@g" "${src_file}"
  1695. sed -i -e "s@{{webhook_config_volume}}@${webhook_config_volume}@g" "${src_file}"
  1696. sed -i -e "s@{{audit_policy_config_mount}}@${audit_policy_config_mount}@g" "${src_file}"
  1697. sed -i -e "s@{{audit_policy_config_volume}}@${audit_policy_config_volume}@g" "${src_file}"
  1698. sed -i -e "s@{{audit_webhook_config_mount}}@${audit_webhook_config_mount}@g" "${src_file}"
  1699. sed -i -e "s@{{audit_webhook_config_volume}}@${audit_webhook_config_volume}@g" "${src_file}"
  1700. sed -i -e "s@{{admission_controller_config_mount}}@${admission_controller_config_mount}@g" "${src_file}"
  1701. sed -i -e "s@{{admission_controller_config_volume}}@${admission_controller_config_volume}@g" "${src_file}"
  1702. sed -i -e "s@{{image_policy_webhook_config_mount}}@${image_policy_webhook_config_mount}@g" "${src_file}"
  1703. sed -i -e "s@{{image_policy_webhook_config_volume}}@${image_policy_webhook_config_volume}@g" "${src_file}"
  1704. cp "${src_file}" "${ETC_MANIFESTS:-/etc/kubernetes/manifests}"
  1705. }
  1706. # Sets-up etcd encryption.
  1707. # Configuration of etcd level encryption consists of the following steps:
  1708. # 1. Writing encryption provider config to disk
  1709. # 2. Adding encryption-provider-config flag to kube-apiserver
  1710. # 3. Add kms-socket-vol and kms-socket-vol-mnt to enable communication with kms-plugin (if requested)
  1711. #
  1712. # Expects parameters:
  1713. # $1 - path to kube-apiserver template
  1714. # $2 - kube-apiserver startup flags (must be passed by reference)
  1715. #
  1716. # Assumes vars (supplied via kube-env):
  1717. # ENCRYPTION_PROVIDER_CONFIG
  1718. # CLOUD_KMS_INTEGRATION
  1719. # ENCRYPTION_PROVIDER_CONFIG_PATH (will default to /etc/srv/kubernetes/encryption-provider-config.yml)
  1720. function setup-etcd-encryption {
  1721. local kube_apiserver_template_path
  1722. local -n kube_api_server_params
  1723. local default_encryption_provider_config_vol
  1724. local default_encryption_provider_config_vol_mnt
  1725. local encryption_provider_config_vol_mnt
  1726. local encryption_provider_config_vol
  1727. local default_kms_socket_dir
  1728. local default_kms_socket_vol_mnt
  1729. local default_kms_socket_vol
  1730. local kms_socket_vol_mnt
  1731. local kms_socket_vol
  1732. local encryption_provider_config_path
  1733. kube_apiserver_template_path="$1"
  1734. if [[ -z "${ENCRYPTION_PROVIDER_CONFIG:-}" ]]; then
  1735. sed -i -e " {
  1736. s@{{encryption_provider_mount}}@@
  1737. s@{{encryption_provider_volume}}@@
  1738. s@{{kms_socket_mount}}@@
  1739. s@{{kms_socket_volume}}@@
  1740. } " "${kube_apiserver_template_path}"
  1741. return
  1742. fi
  1743. kube_api_server_params="$2"
  1744. encryption_provider_config_path=${ENCRYPTION_PROVIDER_CONFIG_PATH:-/etc/srv/kubernetes/encryption-provider-config.yml}
  1745. echo "${ENCRYPTION_PROVIDER_CONFIG}" | base64 --decode > "${encryption_provider_config_path}"
  1746. kube_api_server_params+=" --encryption-provider-config=${encryption_provider_config_path}"
  1747. default_encryption_provider_config_vol=$(echo "{ \"name\": \"encryptionconfig\", \"hostPath\": {\"path\": \"${encryption_provider_config_path}\", \"type\": \"File\"}}" | base64 | tr -d '\r\n')
  1748. default_encryption_provider_config_vol_mnt=$(echo "{ \"name\": \"encryptionconfig\", \"mountPath\": \"${encryption_provider_config_path}\", \"readOnly\": true}" | base64 | tr -d '\r\n')
  1749. encryption_provider_config_vol_mnt=$(echo "${ENCRYPTION_PROVIDER_CONFIG_VOL_MNT:-"${default_encryption_provider_config_vol_mnt}"}" | base64 --decode)
  1750. encryption_provider_config_vol=$(echo "${ENCRYPTION_PROVIDER_CONFIG_VOL:-"${default_encryption_provider_config_vol}"}" | base64 --decode)
  1751. sed -i -e " {
  1752. s@{{encryption_provider_mount}}@${encryption_provider_config_vol_mnt},@
  1753. s@{{encryption_provider_volume}}@${encryption_provider_config_vol},@
  1754. } " "${kube_apiserver_template_path}"
  1755. if [[ -n "${CLOUD_KMS_INTEGRATION:-}" ]]; then
  1756. default_kms_socket_dir="/var/run/kmsplugin"
  1757. default_kms_socket_vol_mnt=$(echo "{ \"name\": \"kmssocket\", \"mountPath\": \"${default_kms_socket_dir}\", \"readOnly\": false}" | base64 | tr -d '\r\n')
  1758. default_kms_socket_vol=$(echo "{ \"name\": \"kmssocket\", \"hostPath\": {\"path\": \"${default_kms_socket_dir}\", \"type\": \"DirectoryOrCreate\"}}" | base64 | tr -d '\r\n')
  1759. kms_socket_vol_mnt=$(echo "${KMS_PLUGIN_SOCKET_VOL_MNT:-"${default_kms_socket_vol_mnt}"}" | base64 --decode)
  1760. kms_socket_vol=$(echo "${KMS_PLUGIN_SOCKET_VOL:-"${default_kms_socket_vol}"}" | base64 --decode)
  1761. sed -i -e " {
  1762. s@{{kms_socket_mount}}@${kms_socket_vol_mnt},@
  1763. s@{{kms_socket_volume}}@${kms_socket_vol},@
  1764. } " "${kube_apiserver_template_path}"
  1765. else
  1766. sed -i -e " {
  1767. s@{{kms_socket_mount}}@@
  1768. s@{{kms_socket_volume}}@@
  1769. } " "${kube_apiserver_template_path}"
  1770. fi
  1771. }
  1772. # Updates node labels used by addons.
  1773. function update-legacy-addon-node-labels() {
  1774. # need kube-apiserver to be ready
  1775. until kubectl get nodes; do
  1776. sleep 5
  1777. done
  1778. update-node-label "beta.kubernetes.io/metadata-proxy-ready=true,cloud.google.com/metadata-proxy-ready!=true" "cloud.google.com/metadata-proxy-ready=true"
  1779. update-node-label "beta.kubernetes.io/kube-proxy-ds-ready=true,node.kubernetes.io/kube-proxy-ds-ready!=true" "node.kubernetes.io/kube-proxy-ds-ready=true"
  1780. update-node-label "beta.kubernetes.io/masq-agent-ds-ready=true,node.kubernetes.io/masq-agent-ds-ready!=true" "node.kubernetes.io/masq-agent-ds-ready=true"
  1781. }
  1782. # A helper function for labeling all nodes matching a given selector.
  1783. # Runs: kubectl label --overwrite nodes -l "${1}" "${2}"
  1784. # Retries on failure
  1785. #
  1786. # $1: label selector of nodes
  1787. # $2: label to apply
  1788. function update-node-label() {
  1789. local selector="$1"
  1790. local label="$2"
  1791. local retries=5
  1792. until (( retries == 0 )); do
  1793. if kubectl label --overwrite nodes -l "${selector}" "${label}"; then
  1794. break
  1795. fi
  1796. (( retries-- ))
  1797. sleep 3
  1798. done
  1799. }
  1800. # Applies encryption provider config.
  1801. # This function may be triggered in two scenarios:
  1802. # 1. Decryption of etcd
  1803. # 2. Encryption of etcd is added after the cluster is deployed
  1804. # Both cases require that the existing secrets in etcd be re-proceeded.
  1805. #
  1806. # Assumes vars (supplied via kube-env):
  1807. # ENCRYPTION_PROVIDER_CONFIG_FORCE
  1808. function apply-encryption-config() {
  1809. if [[ "${ENCRYPTION_PROVIDER_CONFIG_FORCE:-false}" == "false" ]]; then
  1810. return
  1811. fi
  1812. # need kube-apiserver to be ready
  1813. until kubectl get secret; do
  1814. sleep ${ENCRYPTION_PROVIDER_CONFIG_FORCE_DELAY:-5}
  1815. done
  1816. retries=${ENCRYPTION_PROVIDER_CONFIG_FORCE_RETRIES:-5}
  1817. # The command below may fail when a conflict is detected during an update on a secret (something
  1818. # else updated the secret in the middle of our update).
  1819. # TODO: Retry only on errors caused by a conflict.
  1820. until (( retries == 0 )); do
  1821. # forces all secrets to be re-written to etcd, and in the process either encrypting or decrypting them
  1822. # https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/
  1823. if kubectl get secrets --all-namespaces -o json | kubectl replace -f -; then
  1824. break
  1825. fi
  1826. (( retries-- ))
  1827. sleep "${ENCRYPTION_PROVIDER_CONFIG_FORCE_RETRY_SLEEP:-3}"
  1828. done
  1829. }
  1830. # Starts kubernetes controller manager.
  1831. # It prepares the log file, loads the docker image, calculates variables, sets them
  1832. # in the manifest file, and then copies the manifest file to /etc/kubernetes/manifests.
  1833. #
  1834. # Assumed vars (which are calculated in function compute-master-manifest-variables)
  1835. # CLOUD_CONFIG_OPT
  1836. # CLOUD_CONFIG_VOLUME
  1837. # CLOUD_CONFIG_MOUNT
  1838. # DOCKER_REGISTRY
  1839. function start-kube-controller-manager {
  1840. echo "Start kubernetes controller-manager"
  1841. create-kubeconfig "kube-controller-manager" ${KUBE_CONTROLLER_MANAGER_TOKEN}
  1842. prepare-log-file /var/log/kube-controller-manager.log
  1843. # Calculate variables and assemble the command line.
  1844. local params="${CONTROLLER_MANAGER_TEST_LOG_LEVEL:-"--v=2"} ${CONTROLLER_MANAGER_TEST_ARGS:-} ${CLOUD_CONFIG_OPT}"
  1845. params+=" --use-service-account-credentials"
  1846. params+=" --cloud-provider=gce"
  1847. params+=" --kubeconfig=/etc/srv/kubernetes/kube-controller-manager/kubeconfig"
  1848. params+=" --root-ca-file=${CA_CERT_BUNDLE_PATH}"
  1849. params+=" --service-account-private-key-file=${SERVICEACCOUNT_KEY_PATH}"
  1850. if [[ -n "${ENABLE_GARBAGE_COLLECTOR:-}" ]]; then
  1851. params+=" --enable-garbage-collector=${ENABLE_GARBAGE_COLLECTOR}"
  1852. fi
  1853. if [[ -n "${INSTANCE_PREFIX:-}" ]]; then
  1854. params+=" --cluster-name=${INSTANCE_PREFIX}"
  1855. fi
  1856. if [[ -n "${CLUSTER_IP_RANGE:-}" ]]; then
  1857. params+=" --cluster-cidr=${CLUSTER_IP_RANGE}"
  1858. fi
  1859. if [[ -n "${CA_KEY:-}" ]]; then
  1860. params+=" --cluster-signing-cert-file=${CA_CERT_PATH}"
  1861. params+=" --cluster-signing-key-file=${CA_KEY_PATH}"
  1862. fi
  1863. if [[ -n "${SERVICE_CLUSTER_IP_RANGE:-}" ]]; then
  1864. params+=" --service-cluster-ip-range=${SERVICE_CLUSTER_IP_RANGE}"
  1865. fi
  1866. if [[ -n "${CONCURRENT_SERVICE_SYNCS:-}" ]]; then
  1867. params+=" --concurrent-service-syncs=${CONCURRENT_SERVICE_SYNCS}"
  1868. fi
  1869. if [[ "${NETWORK_PROVIDER:-}" == "kubenet" ]]; then
  1870. params+=" --allocate-node-cidrs=true"
  1871. elif [[ -n "${ALLOCATE_NODE_CIDRS:-}" ]]; then
  1872. params+=" --allocate-node-cidrs=${ALLOCATE_NODE_CIDRS}"
  1873. fi
  1874. if [[ -n "${TERMINATED_POD_GC_THRESHOLD:-}" ]]; then
  1875. params+=" --terminated-pod-gc-threshold=${TERMINATED_POD_GC_THRESHOLD}"
  1876. fi
  1877. if [[ "${ENABLE_IP_ALIASES:-}" == 'true' ]]; then
  1878. params+=" --cidr-allocator-type=${NODE_IPAM_MODE}"
  1879. params+=" --configure-cloud-routes=false"
  1880. fi
  1881. if [[ -n "${FEATURE_GATES:-}" ]]; then
  1882. params+=" --feature-gates=${FEATURE_GATES}"
  1883. fi
  1884. if [[ -n "${VOLUME_PLUGIN_DIR:-}" ]]; then
  1885. params+=" --flex-volume-plugin-dir=${VOLUME_PLUGIN_DIR}"
  1886. fi
  1887. if [[ -n "${CLUSTER_SIGNING_DURATION:-}" ]]; then
  1888. params+=" --experimental-cluster-signing-duration=$CLUSTER_SIGNING_DURATION"
  1889. fi
  1890. # Disable using HPA metrics REST clients if metrics-server isn't enabled,
  1891. # or if we want to explicitly disable it by setting HPA_USE_REST_CLIENT.
  1892. if [[ "${ENABLE_METRICS_SERVER:-}" != "true" ]] ||
  1893. [[ "${HPA_USE_REST_CLIENTS:-}" == "false" ]]; then
  1894. params+=" --horizontal-pod-autoscaler-use-rest-clients=false"
  1895. fi
  1896. if [[ -n "${PV_RECYCLER_OVERRIDE_TEMPLATE:-}" ]]; then
  1897. params+=" --pv-recycler-pod-template-filepath-nfs=$PV_RECYCLER_OVERRIDE_TEMPLATE"
  1898. params+=" --pv-recycler-pod-template-filepath-hostpath=$PV_RECYCLER_OVERRIDE_TEMPLATE"
  1899. fi
  1900. if [[ -n "${RUN_CONTROLLERS:-}" ]]; then
  1901. params+=" --controllers=${RUN_CONTROLLERS}"
  1902. fi
  1903. local -r kube_rc_docker_tag=$(cat /home/kubernetes/kube-docker-files/kube-controller-manager.docker_tag)
  1904. local container_env=""
  1905. if [[ -n "${ENABLE_CACHE_MUTATION_DETECTOR:-}" ]]; then
  1906. container_env="\"env\":[{\"name\": \"KUBE_CACHE_MUTATION_DETECTOR\", \"value\": \"${ENABLE_CACHE_MUTATION_DETECTOR}\"}],"
  1907. fi
  1908. local -r src_file="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/kube-controller-manager.manifest"
  1909. # Evaluate variables.
  1910. sed -i -e "s@{{pillar\['kube_docker_registry'\]}}@${DOCKER_REGISTRY}@g" "${src_file}"
  1911. sed -i -e "s@{{pillar\['kube-controller-manager_docker_tag'\]}}@${kube_rc_docker_tag}@g" "${src_file}"
  1912. sed -i -e "s@{{params}}@${params}@g" "${src_file}"
  1913. sed -i -e "s@{{container_env}}@${container_env}@g" ${src_file}
  1914. sed -i -e "s@{{cloud_config_mount}}@${CLOUD_CONFIG_MOUNT}@g" "${src_file}"
  1915. sed -i -e "s@{{cloud_config_volume}}@${CLOUD_CONFIG_VOLUME}@g" "${src_file}"
  1916. sed -i -e "s@{{additional_cloud_config_mount}}@@g" "${src_file}"
  1917. sed -i -e "s@{{additional_cloud_config_volume}}@@g" "${src_file}"
  1918. sed -i -e "s@{{pv_recycler_mount}}@${PV_RECYCLER_MOUNT}@g" "${src_file}"
  1919. sed -i -e "s@{{pv_recycler_volume}}@${PV_RECYCLER_VOLUME}@g" "${src_file}"
  1920. sed -i -e "s@{{flexvolume_hostpath_mount}}@${FLEXVOLUME_HOSTPATH_MOUNT}@g" "${src_file}"
  1921. sed -i -e "s@{{flexvolume_hostpath}}@${FLEXVOLUME_HOSTPATH_VOLUME}@g" "${src_file}"
  1922. sed -i -e "s@{{cpurequest}}@${KUBE_CONTROLLER_MANAGER_CPU_REQUEST}@g" "${src_file}"
  1923. cp "${src_file}" /etc/kubernetes/manifests
  1924. }
  1925. # Starts kubernetes scheduler.
  1926. # It prepares the log file, loads the docker image, calculates variables, sets them
  1927. # in the manifest file, and then copies the manifest file to /etc/kubernetes/manifests.
  1928. #
  1929. # Assumed vars (which are calculated in compute-master-manifest-variables)
  1930. # DOCKER_REGISTRY
  1931. function start-kube-scheduler {
  1932. echo "Start kubernetes scheduler"
  1933. create-kubeconfig "kube-scheduler" ${KUBE_SCHEDULER_TOKEN}
  1934. prepare-log-file /var/log/kube-scheduler.log
  1935. # Calculate variables and set them in the manifest.
  1936. params="${SCHEDULER_TEST_LOG_LEVEL:-"--v=2"} ${SCHEDULER_TEST_ARGS:-}"
  1937. params+=" --kubeconfig=/etc/srv/kubernetes/kube-scheduler/kubeconfig"
  1938. if [[ -n "${FEATURE_GATES:-}" ]]; then
  1939. params+=" --feature-gates=${FEATURE_GATES}"
  1940. fi
  1941. if [[ -n "${SCHEDULING_ALGORITHM_PROVIDER:-}" ]]; then
  1942. params+=" --algorithm-provider=${SCHEDULING_ALGORITHM_PROVIDER}"
  1943. fi
  1944. if [[ -n "${SCHEDULER_POLICY_CONFIG:-}" ]]; then
  1945. create-kubescheduler-policy-config
  1946. params+=" --use-legacy-policy-config"
  1947. params+=" --policy-config-file=/etc/srv/kubernetes/kube-scheduler/policy-config"
  1948. fi
  1949. local -r kube_scheduler_docker_tag=$(cat "${KUBE_HOME}/kube-docker-files/kube-scheduler.docker_tag")
  1950. # Remove salt comments and replace variables with values.
  1951. local -r src_file="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/kube-scheduler.manifest"
  1952. sed -i -e "s@{{params}}@${params}@g" "${src_file}"
  1953. sed -i -e "s@{{pillar\['kube_docker_registry'\]}}@${DOCKER_REGISTRY}@g" "${src_file}"
  1954. sed -i -e "s@{{pillar\['kube-scheduler_docker_tag'\]}}@${kube_scheduler_docker_tag}@g" "${src_file}"
  1955. sed -i -e "s@{{cpurequest}}@${KUBE_SCHEDULER_CPU_REQUEST}@g" "${src_file}"
  1956. cp "${src_file}" /etc/kubernetes/manifests
  1957. }
  1958. # Starts cluster autoscaler.
  1959. # Assumed vars (which are calculated in function compute-master-manifest-variables)
  1960. # CLOUD_CONFIG_OPT
  1961. # CLOUD_CONFIG_VOLUME
  1962. # CLOUD_CONFIG_MOUNT
  1963. function start-cluster-autoscaler {
  1964. if [[ "${ENABLE_CLUSTER_AUTOSCALER:-}" == "true" ]]; then
  1965. echo "Start kubernetes cluster autoscaler"
  1966. setup-addon-manifests "addons" "rbac/cluster-autoscaler"
  1967. create-kubeconfig "cluster-autoscaler" ${KUBE_CLUSTER_AUTOSCALER_TOKEN}
  1968. prepare-log-file /var/log/cluster-autoscaler.log
  1969. # Remove salt comments and replace variables with values
  1970. local -r src_file="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/cluster-autoscaler.manifest"
  1971. local params="${AUTOSCALER_MIG_CONFIG} ${CLOUD_CONFIG_OPT} ${AUTOSCALER_EXPANDER_CONFIG:---expander=price}"
  1972. params+=" --kubeconfig=/etc/srv/kubernetes/cluster-autoscaler/kubeconfig"
  1973. # split the params into separate arguments passed to binary
  1974. local params_split
  1975. params_split=$(eval "for param in $params; do echo -n \\\"\$param\\\",; done")
  1976. params_split=${params_split%?}
  1977. sed -i -e "s@{{params}}@${params_split}@g" "${src_file}"
  1978. sed -i -e "s@{{cloud_config_mount}}@${CLOUD_CONFIG_MOUNT}@g" "${src_file}"
  1979. sed -i -e "s@{{cloud_config_volume}}@${CLOUD_CONFIG_VOLUME}@g" "${src_file}"
  1980. sed -i -e "s@{%.*%}@@g" "${src_file}"
  1981. cp "${src_file}" /etc/kubernetes/manifests
  1982. fi
  1983. }
  1984. # A helper function for setting up addon manifests.
  1985. #
  1986. # $1: addon category under /etc/kubernetes
  1987. # $2: manifest source dir
  1988. # $3: (optional) auxiliary manifest source dir
  1989. function setup-addon-manifests {
  1990. local -r src_dir="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty"
  1991. local -r dst_dir="/etc/kubernetes/$1/$2"
  1992. copy-manifests "${src_dir}/$2" "${dst_dir}"
  1993. # If the PodSecurityPolicy admission controller is enabled,
  1994. # set up the corresponding addon policies.
  1995. if [[ "${ENABLE_POD_SECURITY_POLICY:-}" == "true" ]]; then
  1996. local -r psp_dir="${src_dir}/${3:-$2}/podsecuritypolicies"
  1997. if [[ -d "${psp_dir}" ]]; then
  1998. copy-manifests "${psp_dir}" "${dst_dir}"
  1999. fi
  2000. fi
  2001. if [[ "${ENABLE_NODE_TERMINATION_HANDLER:-}" == "true" ]]; then
  2002. local -r nth_dir="${src_dir}/${3:-$2}/node-termination-handler"
  2003. if [[ -d "${nth_dir}" ]]; then
  2004. copy-manifests "${nth_dir}" "${dst_dir}"
  2005. fi
  2006. fi
  2007. }
  2008. # A function that downloads extra addons from a URL and puts them in the GCI
  2009. # manifests directory.
  2010. function download-extra-addons {
  2011. local -r out_dir="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/gce-extras"
  2012. mkdir -p "${out_dir}"
  2013. local curl_cmd=(
  2014. "curl"
  2015. "--fail"
  2016. "--retry" "5"
  2017. "--retry-delay" "3"
  2018. "--silent"
  2019. "--show-error"
  2020. )
  2021. if [[ -n "${CURL_RETRY_CONNREFUSED:-}" ]]; then
  2022. curl_cmd+=("${CURL_RETRY_CONNREFUSED}")
  2023. fi
  2024. if [[ -n "${EXTRA_ADDONS_HEADER:-}" ]]; then
  2025. curl_cmd+=("-H" "${EXTRA_ADDONS_HEADER}")
  2026. fi
  2027. curl_cmd+=("-o" "${out_dir}/extras.json")
  2028. curl_cmd+=("${EXTRA_ADDONS_URL}")
  2029. "${curl_cmd[@]}"
  2030. }
  2031. # A function that fetches a GCE metadata value and echoes it out.
  2032. #
  2033. # $1: URL path after /computeMetadata/v1/ (without heading slash).
  2034. function get-metadata-value {
  2035. curl \
  2036. --retry 5 \
  2037. --retry-delay 3 \
  2038. ${CURL_RETRY_CONNREFUSED} \
  2039. --fail \
  2040. --silent \
  2041. -H 'Metadata-Flavor: Google' \
  2042. "http://metadata/computeMetadata/v1/${1}"
  2043. }
  2044. # A helper function for copying manifests and setting dir/files
  2045. # permissions.
  2046. #
  2047. # $1: absolute source dir
  2048. # $2: absolute destination dir
  2049. function copy-manifests {
  2050. local -r src_dir="$1"
  2051. local -r dst_dir="$2"
  2052. if [[ ! -d "${dst_dir}" ]]; then
  2053. mkdir -p "${dst_dir}"
  2054. fi
  2055. local files=$(find "${src_dir}" -maxdepth 1 -name "*.yaml")
  2056. if [[ -n "${files}" ]]; then
  2057. cp "${src_dir}/"*.yaml "${dst_dir}"
  2058. fi
  2059. files=$(find "${src_dir}" -maxdepth 1 -name "*.json")
  2060. if [[ -n "${files}" ]]; then
  2061. cp "${src_dir}/"*.json "${dst_dir}"
  2062. fi
  2063. files=$(find "${src_dir}" -maxdepth 1 -name "*.yaml.in")
  2064. if [[ -n "${files}" ]]; then
  2065. cp "${src_dir}/"*.yaml.in "${dst_dir}"
  2066. fi
  2067. chown -R root:root "${dst_dir}"
  2068. chmod 755 "${dst_dir}"
  2069. chmod 644 "${dst_dir}"/*
  2070. }
  2071. # Fluentd resources are modified using ScalingPolicy CR, which may not be
  2072. # available at this point. Run this as a background process.
  2073. function wait-for-apiserver-and-update-fluentd {
  2074. local any_overrides=false
  2075. if [[ -n "${FLUENTD_GCP_MEMORY_LIMIT:-}" ]]; then
  2076. any_overrides=true
  2077. fi
  2078. if [[ -n "${FLUENTD_GCP_CPU_REQUEST:-}" ]]; then
  2079. any_overrides=true
  2080. fi
  2081. if [[ -n "${FLUENTD_GCP_MEMORY_REQUEST:-}" ]]; then
  2082. any_overrides=true
  2083. fi
  2084. if ! $any_overrides; then
  2085. # Nothing to do here.
  2086. exit
  2087. fi
  2088. # Wait until ScalingPolicy CRD is in place.
  2089. until kubectl get scalingpolicies.scalingpolicy.kope.io
  2090. do
  2091. sleep 10
  2092. done
  2093. # Single-shot, not managed by addon manager. Can be later modified or removed
  2094. # at will.
  2095. cat <<EOF | kubectl apply -f -
  2096. apiVersion: scalingpolicy.kope.io/v1alpha1
  2097. kind: ScalingPolicy
  2098. metadata:
  2099. name: fluentd-gcp-scaling-policy
  2100. namespace: kube-system
  2101. spec:
  2102. containers:
  2103. - name: fluentd-gcp
  2104. resources:
  2105. requests:
  2106. - resource: cpu
  2107. base: ${FLUENTD_GCP_CPU_REQUEST:-}
  2108. - resource: memory
  2109. base: ${FLUENTD_GCP_MEMORY_REQUEST:-}
  2110. limits:
  2111. - resource: memory
  2112. base: ${FLUENTD_GCP_MEMORY_LIMIT:-}
  2113. EOF
  2114. }
  2115. # Trigger background process that will ultimately update fluentd resource
  2116. # requirements.
  2117. function start-fluentd-resource-update {
  2118. wait-for-apiserver-and-update-fluentd &
  2119. }
  2120. # Update {{ fluentd_container_runtime_service }} with actual container runtime name,
  2121. # and {{ container_runtime_endpoint }} with actual container runtime
  2122. # endpoint.
  2123. function update-container-runtime {
  2124. local -r file="$1"
  2125. local -r container_runtime_endpoint="${CONTAINER_RUNTIME_ENDPOINT:-unix:///var/run/dockershim.sock}"
  2126. sed -i \
  2127. -e "s@{{ *fluentd_container_runtime_service *}}@${FLUENTD_CONTAINER_RUNTIME_SERVICE:-${CONTAINER_RUNTIME_NAME:-docker}}@g" \
  2128. -e "s@{{ *container_runtime_endpoint *}}@${container_runtime_endpoint#unix://}@g" \
  2129. "${file}"
  2130. }
  2131. # Remove configuration in yaml file if node journal is not enabled.
  2132. function update-node-journal {
  2133. local -r configmap_yaml="$1"
  2134. if [[ "${ENABLE_NODE_JOURNAL:-}" != "true" ]]; then
  2135. # Removes all lines between two patterns (throws away node-journal)
  2136. sed -i -e "/# BEGIN_NODE_JOURNAL/,/# END_NODE_JOURNAL/d" "${configmap_yaml}"
  2137. fi
  2138. }
  2139. # Updates parameters in yaml file for prometheus-to-sd configuration, or
  2140. # removes component if it is disabled.
  2141. function update-prometheus-to-sd-parameters {
  2142. if [[ "${ENABLE_PROMETHEUS_TO_SD:-}" == "true" ]]; then
  2143. sed -i -e "s@{{ *prometheus_to_sd_prefix *}}@${PROMETHEUS_TO_SD_PREFIX}@g" "$1"
  2144. sed -i -e "s@{{ *prometheus_to_sd_endpoint *}}@${PROMETHEUS_TO_SD_ENDPOINT}@g" "$1"
  2145. else
  2146. # Removes all lines between two patterns (throws away prometheus-to-sd)
  2147. sed -i -e "/# BEGIN_PROMETHEUS_TO_SD/,/# END_PROMETHEUS_TO_SD/d" "$1"
  2148. fi
  2149. }
  2150. # Updates parameters in yaml file for prometheus-to-sd configuration in daemon sets, or
  2151. # removes component if it is disabled.
  2152. function update-daemon-set-prometheus-to-sd-parameters {
  2153. if [[ "${DISABLE_PROMETHEUS_TO_SD_IN_DS:-}" == "true" ]]; then
  2154. # Removes all lines between two patterns (throws away prometheus-to-sd)
  2155. sed -i -e "/# BEGIN_PROMETHEUS_TO_SD/,/# END_PROMETHEUS_TO_SD/d" "$1"
  2156. else
  2157. update-prometheus-to-sd-parameters $1
  2158. fi
  2159. }
  2160. # Updates parameters in yaml file for event-exporter configuration
  2161. function update-event-exporter {
  2162. local -r stackdriver_resource_model="${LOGGING_STACKDRIVER_RESOURCE_TYPES:-old}"
  2163. sed -i -e "s@{{ exporter_sd_resource_model }}@${stackdriver_resource_model}@g" "$1"
  2164. }
  2165. function update-dashboard-controller {
  2166. if [ -n "${CUSTOM_KUBE_DASHBOARD_BANNER:-}" ]; then
  2167. sed -i -e "s@\( \+\)# PLATFORM-SPECIFIC ARGS HERE@\1- --system-banner=${CUSTOM_KUBE_DASHBOARD_BANNER}\n\1- --system-banner-severity=WARNING@" "$1"
  2168. fi
  2169. }
  2170. # Sets up the manifests of coreDNS for k8s addons.
  2171. function setup-coredns-manifest {
  2172. setup-addon-manifests "addons" "0-dns/coredns"
  2173. local -r coredns_file="${dst_dir}/0-dns/coredns/coredns.yaml"
  2174. mv "${dst_dir}/0-dns/coredns/coredns.yaml.in" "${coredns_file}"
  2175. # Replace the salt configurations with variable values.
  2176. sed -i -e "s@{{ *pillar\['dns_domain'\] *}}@${DNS_DOMAIN}@g" "${coredns_file}"
  2177. sed -i -e "s@{{ *pillar\['dns_server'\] *}}@${DNS_SERVER_IP}@g" "${coredns_file}"
  2178. sed -i -e "s@{{ *pillar\['service_cluster_ip_range'\] *}}@${SERVICE_CLUSTER_IP_RANGE}@g" "${coredns_file}"
  2179. sed -i -e "s@{{ *pillar\['dns_memory_limit'\] *}}@${DNS_MEMORY_LIMIT:-170Mi}@g" "${coredns_file}"
  2180. if [[ "${ENABLE_DNS_HORIZONTAL_AUTOSCALER:-}" == "true" ]]; then
  2181. setup-addon-manifests "addons" "dns-horizontal-autoscaler" "gce"
  2182. local -r dns_autoscaler_file="${dst_dir}/dns-horizontal-autoscaler/dns-horizontal-autoscaler.yaml"
  2183. sed -i'' -e "s@{{.Target}}@${COREDNS_AUTOSCALER}@g" "${dns_autoscaler_file}"
  2184. fi
  2185. }
  2186. # Sets up the manifests of Fluentd configmap and yamls for k8s addons.
  2187. function setup-fluentd {
  2188. local -r dst_dir="$1"
  2189. local -r fluentd_gcp_yaml="${dst_dir}/fluentd-gcp/fluentd-gcp-ds.yaml"
  2190. local -r fluentd_gcp_scaler_yaml="${dst_dir}/fluentd-gcp/scaler-deployment.yaml"
  2191. # Ingest logs against new resources like "k8s_container" and "k8s_node" if
  2192. # LOGGING_STACKDRIVER_RESOURCE_TYPES is "new".
  2193. # Ingest logs against old resources like "gke_container" and "gce_instance" if
  2194. # LOGGING_STACKDRIVER_RESOURCE_TYPES is "old".
  2195. if [[ "${LOGGING_STACKDRIVER_RESOURCE_TYPES:-old}" == "new" ]]; then
  2196. local -r fluentd_gcp_configmap_yaml="${dst_dir}/fluentd-gcp/fluentd-gcp-configmap.yaml"
  2197. fluentd_gcp_configmap_name="fluentd-gcp-config"
  2198. else
  2199. local -r fluentd_gcp_configmap_yaml="${dst_dir}/fluentd-gcp/fluentd-gcp-configmap-old.yaml"
  2200. fluentd_gcp_configmap_name="fluentd-gcp-config-old"
  2201. fi
  2202. sed -i -e "s@{{ fluentd_gcp_configmap_name }}@${fluentd_gcp_configmap_name}@g" "${fluentd_gcp_yaml}"
  2203. fluentd_gcp_yaml_version="${FLUENTD_GCP_YAML_VERSION:-v3.2.0}"
  2204. sed -i -e "s@{{ fluentd_gcp_yaml_version }}@${fluentd_gcp_yaml_version}@g" "${fluentd_gcp_yaml}"
  2205. sed -i -e "s@{{ fluentd_gcp_yaml_version }}@${fluentd_gcp_yaml_version}@g" "${fluentd_gcp_scaler_yaml}"
  2206. fluentd_gcp_version="${FLUENTD_GCP_VERSION:-1.6.8}"
  2207. sed -i -e "s@{{ fluentd_gcp_version }}@${fluentd_gcp_version}@g" "${fluentd_gcp_yaml}"
  2208. update-daemon-set-prometheus-to-sd-parameters ${fluentd_gcp_yaml}
  2209. start-fluentd-resource-update ${fluentd_gcp_yaml}
  2210. update-container-runtime ${fluentd_gcp_configmap_yaml}
  2211. update-node-journal ${fluentd_gcp_configmap_yaml}
  2212. }
  2213. # Sets up the manifests of kube-dns for k8s addons.
  2214. function setup-kube-dns-manifest {
  2215. setup-addon-manifests "addons" "0-dns/kube-dns"
  2216. local -r kubedns_file="${dst_dir}/0-dns/kube-dns/kube-dns.yaml"
  2217. mv "${dst_dir}/0-dns/kube-dns/kube-dns.yaml.in" "${kubedns_file}"
  2218. if [ -n "${CUSTOM_KUBE_DNS_YAML:-}" ]; then
  2219. # Replace with custom GKE kube-dns deployment.
  2220. cat > "${kubedns_file}" <<EOF
  2221. $CUSTOM_KUBE_DNS_YAML
  2222. EOF
  2223. update-prometheus-to-sd-parameters ${kubedns_file}
  2224. fi
  2225. # Replace the salt configurations with variable values.
  2226. sed -i -e "s@{{ *pillar\['dns_domain'\] *}}@${DNS_DOMAIN}@g" "${kubedns_file}"
  2227. sed -i -e "s@{{ *pillar\['dns_server'\] *}}@${DNS_SERVER_IP}@g" "${kubedns_file}"
  2228. sed -i -e "s@{{ *pillar\['dns_memory_limit'\] *}}@${DNS_MEMORY_LIMIT:-170Mi}@g" "${kubedns_file}"
  2229. if [[ "${ENABLE_DNS_HORIZONTAL_AUTOSCALER:-}" == "true" ]]; then
  2230. setup-addon-manifests "addons" "dns-horizontal-autoscaler" "gce"
  2231. local -r dns_autoscaler_file="${dst_dir}/dns-horizontal-autoscaler/dns-horizontal-autoscaler.yaml"
  2232. sed -i'' -e "s@{{.Target}}@${KUBEDNS_AUTOSCALER}@g" "${dns_autoscaler_file}"
  2233. fi
  2234. }
  2235. # Sets up the manifests of local dns cache agent for k8s addons.
  2236. function setup-nodelocaldns-manifest {
  2237. setup-addon-manifests "addons" "0-dns/nodelocaldns"
  2238. local -r localdns_file="${dst_dir}/0-dns/nodelocaldns/nodelocaldns.yaml"
  2239. # Replace the sed configurations with variable values.
  2240. sed -i -e "s/__PILLAR__DNS__DOMAIN__/${DNS_DOMAIN}/g" "${localdns_file}"
  2241. sed -i -e "s/__PILLAR__DNS__SERVER__/${DNS_SERVER_IP}/g" "${localdns_file}"
  2242. sed -i -e "s/__PILLAR__LOCAL__DNS__/${LOCAL_DNS_IP}/g" "${localdns_file}"
  2243. }
  2244. # Sets up the manifests of netd for k8s addons.
  2245. function setup-netd-manifest {
  2246. local -r netd_file="${dst_dir}/netd/netd.yaml"
  2247. mkdir -p "${dst_dir}/netd"
  2248. touch "${netd_file}"
  2249. if [ -n "${CUSTOM_NETD_YAML:-}" ]; then
  2250. # Replace with custom GCP netd deployment.
  2251. cat > "${netd_file}" <<EOF
  2252. $CUSTOM_NETD_YAML
  2253. EOF
  2254. fi
  2255. }
  2256. # A helper function to set up a custom yaml for a k8s addon.
  2257. #
  2258. # $1: addon category under /etc/kubernetes
  2259. # $2: manifest source dir
  2260. # $3: manifest file
  2261. # $4: custom yaml
  2262. function setup-addon-custom-yaml {
  2263. local -r manifest_path="/etc/kubernetes/$1/$2/$3"
  2264. local -r custom_yaml="$4"
  2265. if [ -n "${custom_yaml:-}" ]; then
  2266. # Replace with custom manifest.
  2267. cat > "${manifest_path}" <<EOF
  2268. $custom_yaml
  2269. EOF
  2270. fi
  2271. }
  2272. # Prepares the manifests of k8s addons, and starts the addon manager.
  2273. # Vars assumed:
  2274. # CLUSTER_NAME
  2275. function start-kube-addons {
  2276. echo "Prepare kube-addons manifests and start kube addon manager"
  2277. local -r src_dir="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty"
  2278. local -r dst_dir="/etc/kubernetes/addons"
  2279. create-kubeconfig "addon-manager" ${ADDON_MANAGER_TOKEN}
  2280. # prep addition kube-up specific rbac objects
  2281. setup-addon-manifests "addons" "rbac/kubelet-api-auth"
  2282. setup-addon-manifests "addons" "rbac/kubelet-cert-rotation"
  2283. if [[ "${REGISTER_MASTER_KUBELET:-false}" == "true" ]]; then
  2284. setup-addon-manifests "addons" "rbac/legacy-kubelet-user"
  2285. else
  2286. setup-addon-manifests "addons" "rbac/legacy-kubelet-user-disable"
  2287. fi
  2288. if [[ "${ENABLE_POD_SECURITY_POLICY:-}" == "true" ]]; then
  2289. setup-addon-manifests "addons" "podsecuritypolicies"
  2290. fi
  2291. # Set up manifests of other addons.
  2292. if [[ "${KUBE_PROXY_DAEMONSET:-}" == "true" ]]; then
  2293. if [ -n "${CUSTOM_KUBE_PROXY_YAML:-}" ]; then
  2294. # Replace with custom GKE kube proxy.
  2295. cat > "$src_dir/kube-proxy/kube-proxy-ds.yaml" <<EOF
  2296. $CUSTOM_KUBE_PROXY_YAML
  2297. EOF
  2298. update-daemon-set-prometheus-to-sd-parameters "$src_dir/kube-proxy/kube-proxy-ds.yaml"
  2299. fi
  2300. prepare-kube-proxy-manifest-variables "$src_dir/kube-proxy/kube-proxy-ds.yaml"
  2301. setup-addon-manifests "addons" "kube-proxy"
  2302. fi
  2303. # Setup prometheus stack for monitoring kubernetes cluster
  2304. if [[ "${ENABLE_PROMETHEUS_MONITORING:-}" == "true" ]]; then
  2305. setup-addon-manifests "addons" "prometheus"
  2306. fi
  2307. # Setup cluster monitoring using heapster
  2308. if [[ "${ENABLE_CLUSTER_MONITORING:-}" == "influxdb" ]] || \
  2309. [[ "${ENABLE_CLUSTER_MONITORING:-}" == "google" ]] || \
  2310. [[ "${ENABLE_CLUSTER_MONITORING:-}" == "stackdriver" ]] || \
  2311. [[ "${ENABLE_CLUSTER_MONITORING:-}" == "standalone" ]] || \
  2312. [[ "${ENABLE_CLUSTER_MONITORING:-}" == "googleinfluxdb" ]]; then
  2313. local -r file_dir="cluster-monitoring/${ENABLE_CLUSTER_MONITORING}"
  2314. setup-addon-manifests "addons" "cluster-monitoring"
  2315. setup-addon-manifests "addons" "${file_dir}"
  2316. # Replace the salt configurations with variable values.
  2317. base_metrics_memory="${HEAPSTER_GCP_BASE_MEMORY:-140Mi}"
  2318. base_eventer_memory="190Mi"
  2319. base_metrics_cpu="${HEAPSTER_GCP_BASE_CPU:-80m}"
  2320. nanny_memory="90Mi"
  2321. local heapster_min_cluster_size="16"
  2322. local metrics_memory_per_node="${HEAPSTER_GCP_MEMORY_PER_NODE:-4}"
  2323. local -r metrics_cpu_per_node="${HEAPSTER_GCP_CPU_PER_NODE:-0.5}"
  2324. local -r eventer_memory_per_node="500"
  2325. local -r nanny_memory_per_node="200"
  2326. if [[ "${ENABLE_SYSTEM_ADDON_RESOURCE_OPTIMIZATIONS:-}" == "true" ]]; then
  2327. base_metrics_memory="${HEAPSTER_GCP_BASE_MEMORY:-100Mi}"
  2328. base_metrics_cpu="${HEAPSTER_GCP_BASE_CPU:-10m}"
  2329. metrics_memory_per_node="${HEAPSTER_GCP_MEMORY_PER_NODE:-4}"
  2330. heapster_min_cluster_size="5"
  2331. fi
  2332. if [[ -n "${NUM_NODES:-}" && "${NUM_NODES}" -ge 1 ]]; then
  2333. num_kube_nodes="$((${NUM_NODES}+1))"
  2334. nanny_memory="$((${num_kube_nodes} * ${nanny_memory_per_node} + 90 * 1024))Ki"
  2335. fi
  2336. controller_yaml="${dst_dir}/${file_dir}"
  2337. if [[ "${ENABLE_CLUSTER_MONITORING:-}" == "googleinfluxdb" ]]; then
  2338. controller_yaml="${controller_yaml}/heapster-controller-combined.yaml"
  2339. else
  2340. controller_yaml="${controller_yaml}/heapster-controller.yaml"
  2341. fi
  2342. sed -i -e "s@{{ cluster_name }}@${CLUSTER_NAME}@g" "${controller_yaml}"
  2343. sed -i -e "s@{{ cluster_location }}@${ZONE}@g" "${controller_yaml}"
  2344. sed -i -e "s@{{ *base_metrics_memory *}}@${base_metrics_memory}@g" "${controller_yaml}"
  2345. sed -i -e "s@{{ *base_metrics_cpu *}}@${base_metrics_cpu}@g" "${controller_yaml}"
  2346. sed -i -e "s@{{ *base_eventer_memory *}}@${base_eventer_memory}@g" "${controller_yaml}"
  2347. sed -i -e "s@{{ *metrics_memory_per_node *}}@${metrics_memory_per_node}@g" "${controller_yaml}"
  2348. sed -i -e "s@{{ *eventer_memory_per_node *}}@${eventer_memory_per_node}@g" "${controller_yaml}"
  2349. sed -i -e "s@{{ *nanny_memory *}}@${nanny_memory}@g" "${controller_yaml}"
  2350. sed -i -e "s@{{ *metrics_cpu_per_node *}}@${metrics_cpu_per_node}@g" "${controller_yaml}"
  2351. sed -i -e "s@{{ *heapster_min_cluster_size *}}@${heapster_min_cluster_size}@g" "${controller_yaml}"
  2352. update-prometheus-to-sd-parameters ${controller_yaml}
  2353. if [[ "${ENABLE_CLUSTER_MONITORING:-}" == "stackdriver" ]]; then
  2354. use_old_resources="${HEAPSTER_USE_OLD_STACKDRIVER_RESOURCES:-true}"
  2355. use_new_resources="${HEAPSTER_USE_NEW_STACKDRIVER_RESOURCES:-false}"
  2356. sed -i -e "s@{{ use_old_resources }}@${use_old_resources}@g" "${controller_yaml}"
  2357. sed -i -e "s@{{ use_new_resources }}@${use_new_resources}@g" "${controller_yaml}"
  2358. fi
  2359. fi
  2360. if [[ "${ENABLE_CLUSTER_MONITORING:-}" == "stackdriver" ]] ||
  2361. ([[ "${ENABLE_CLUSTER_LOGGING:-}" == "true" ]] &&
  2362. [[ "${LOGGING_DESTINATION:-}" == "gcp" ]]); then
  2363. if [[ "${ENABLE_METADATA_AGENT:-}" == "stackdriver" ]]; then
  2364. metadata_agent_cpu_request="${METADATA_AGENT_CPU_REQUEST:-40m}"
  2365. metadata_agent_memory_request="${METADATA_AGENT_MEMORY_REQUEST:-50Mi}"
  2366. metadata_agent_cluster_level_cpu_request="${METADATA_AGENT_CLUSTER_LEVEL_CPU_REQUEST:-40m}"
  2367. metadata_agent_cluster_level_memory_request="${METADATA_AGENT_CLUSTER_LEVEL_MEMORY_REQUEST:-50Mi}"
  2368. setup-addon-manifests "addons" "metadata-agent/stackdriver"
  2369. metadata_agent_yaml="${dst_dir}/metadata-agent/stackdriver/metadata-agent.yaml"
  2370. sed -i -e "s@{{ metadata_agent_cpu_request }}@${metadata_agent_cpu_request}@g" "${metadata_agent_yaml}"
  2371. sed -i -e "s@{{ metadata_agent_memory_request }}@${metadata_agent_memory_request}@g" "${metadata_agent_yaml}"
  2372. sed -i -e "s@{{ metadata_agent_cluster_level_cpu_request }}@${metadata_agent_cluster_level_cpu_request}@g" "${metadata_agent_yaml}"
  2373. sed -i -e "s@{{ metadata_agent_cluster_level_memory_request }}@${metadata_agent_cluster_level_memory_request}@g" "${metadata_agent_yaml}"
  2374. fi
  2375. fi
  2376. if [[ "${ENABLE_METRICS_SERVER:-}" == "true" ]]; then
  2377. setup-addon-manifests "addons" "metrics-server"
  2378. base_metrics_server_cpu="40m"
  2379. base_metrics_server_memory="40Mi"
  2380. metrics_server_memory_per_node="4"
  2381. metrics_server_min_cluster_size="16"
  2382. if [[ "${ENABLE_SYSTEM_ADDON_RESOURCE_OPTIMIZATIONS:-}" == "true" ]]; then
  2383. base_metrics_server_cpu="40m"
  2384. base_metrics_server_memory="35Mi"
  2385. metrics_server_memory_per_node="4"
  2386. metrics_server_min_cluster_size="5"
  2387. fi
  2388. local -r metrics_server_yaml="${dst_dir}/metrics-server/metrics-server-deployment.yaml"
  2389. sed -i -e "s@{{ base_metrics_server_cpu }}@${base_metrics_server_cpu}@g" "${metrics_server_yaml}"
  2390. sed -i -e "s@{{ base_metrics_server_memory }}@${base_metrics_server_memory}@g" "${metrics_server_yaml}"
  2391. sed -i -e "s@{{ metrics_server_memory_per_node }}@${metrics_server_memory_per_node}@g" "${metrics_server_yaml}"
  2392. sed -i -e "s@{{ metrics_server_min_cluster_size }}@${metrics_server_min_cluster_size}@g" "${metrics_server_yaml}"
  2393. fi
  2394. if [[ "${ENABLE_NVIDIA_GPU_DEVICE_PLUGIN:-}" == "true" ]]; then
  2395. setup-addon-manifests "addons" "device-plugins/nvidia-gpu"
  2396. fi
  2397. if [[ "${ENABLE_NODE_TERMINATION_HANDLER:-}" == "true" ]]; then
  2398. setup-addon-manifests "addons" "node-termination-handler"
  2399. setup-node-termination-handler-manifest
  2400. fi
  2401. if [[ "${ENABLE_CLUSTER_DNS:-}" == "true" ]]; then
  2402. # Create a new directory for the DNS addon and prepend a "0" on the name.
  2403. # Prepending "0" to the directory ensures that add-on manager
  2404. # creates the dns service first. This ensures no other add-on
  2405. # can "steal" the designated DNS clusterIP.
  2406. BASE_ADDON_DIR=${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty
  2407. BASE_DNS_DIR=${BASE_ADDON_DIR}/dns
  2408. NEW_DNS_DIR=${BASE_ADDON_DIR}/0-dns
  2409. mkdir ${NEW_DNS_DIR} && mv ${BASE_DNS_DIR}/* ${NEW_DNS_DIR} && rm -r ${BASE_DNS_DIR}
  2410. if [[ "${CLUSTER_DNS_CORE_DNS:-}" == "true" ]]; then
  2411. setup-coredns-manifest
  2412. else
  2413. setup-kube-dns-manifest
  2414. fi
  2415. if [[ "${ENABLE_NODELOCAL_DNS:-}" == "true" ]]; then
  2416. setup-nodelocaldns-manifest
  2417. fi
  2418. fi
  2419. if [[ "${ENABLE_NETD:-}" == "true" ]]; then
  2420. setup-netd-manifest
  2421. fi
  2422. if [[ "${ENABLE_NODE_LOGGING:-}" == "true" ]] && \
  2423. [[ "${LOGGING_DESTINATION:-}" == "elasticsearch" ]] && \
  2424. [[ "${ENABLE_CLUSTER_LOGGING:-}" == "true" ]]; then
  2425. setup-addon-manifests "addons" "fluentd-elasticsearch"
  2426. local -r fluentd_es_configmap_yaml="${dst_dir}/fluentd-elasticsearch/fluentd-es-configmap.yaml"
  2427. update-container-runtime ${fluentd_es_configmap_yaml}
  2428. fi
  2429. if [[ "${ENABLE_NODE_LOGGING:-}" == "true" ]] && \
  2430. [[ "${LOGGING_DESTINATION:-}" == "gcp" ]]; then
  2431. setup-addon-manifests "addons" "fluentd-gcp"
  2432. setup-fluentd ${dst_dir}
  2433. local -r event_exporter_yaml="${dst_dir}/fluentd-gcp/event-exporter.yaml"
  2434. update-event-exporter ${event_exporter_yaml}
  2435. update-prometheus-to-sd-parameters ${event_exporter_yaml}
  2436. fi
  2437. if [[ "${ENABLE_CLUSTER_UI:-}" == "true" ]]; then
  2438. setup-addon-manifests "addons" "dashboard"
  2439. local -r dashboard_controller_yaml="${dst_dir}/dashboard/dashboard-controller.yaml"
  2440. update-dashboard-controller ${dashboard_controller_yaml}
  2441. fi
  2442. if [[ "${ENABLE_NODE_PROBLEM_DETECTOR:-}" == "daemonset" ]]; then
  2443. setup-addon-manifests "addons" "node-problem-detector"
  2444. fi
  2445. if [[ "${ENABLE_NODE_PROBLEM_DETECTOR:-}" == "standalone" ]]; then
  2446. # Setup role binding for standalone node problem detector.
  2447. setup-addon-manifests "addons" "node-problem-detector/standalone" "node-problem-detector"
  2448. fi
  2449. if echo "${ADMISSION_CONTROL:-}" | grep -q "LimitRanger"; then
  2450. setup-addon-manifests "admission-controls" "limit-range" "gce"
  2451. fi
  2452. if [[ "${NETWORK_POLICY_PROVIDER:-}" == "calico" ]]; then
  2453. setup-addon-manifests "addons" "calico-policy-controller"
  2454. setup-addon-custom-yaml "addons" "calico-policy-controller" "calico-node-daemonset.yaml" "${CUSTOM_CALICO_NODE_DAEMONSET_YAML:-}"
  2455. setup-addon-custom-yaml "addons" "calico-policy-controller" "typha-deployment.yaml" "${CUSTOM_TYPHA_DEPLOYMENT_YAML:-}"
  2456. # Configure Calico CNI directory.
  2457. local -r ds_file="${dst_dir}/calico-policy-controller/calico-node-daemonset.yaml"
  2458. sed -i -e "s@__CALICO_CNI_DIR__@/home/kubernetes/bin@g" "${ds_file}"
  2459. fi
  2460. if [[ "${ENABLE_DEFAULT_STORAGE_CLASS:-}" == "true" ]]; then
  2461. setup-addon-manifests "addons" "storage-class/gce"
  2462. fi
  2463. if [[ "${ENABLE_IP_MASQ_AGENT:-}" == "true" ]]; then
  2464. setup-addon-manifests "addons" "ip-masq-agent"
  2465. fi
  2466. if [[ "${ENABLE_METADATA_CONCEALMENT:-}" == "true" ]]; then
  2467. setup-addon-manifests "addons" "metadata-proxy/gce"
  2468. local -r metadata_proxy_yaml="${dst_dir}/metadata-proxy/gce/metadata-proxy.yaml"
  2469. update-daemon-set-prometheus-to-sd-parameters ${metadata_proxy_yaml}
  2470. fi
  2471. if [[ "${ENABLE_ISTIO:-}" == "true" ]]; then
  2472. if [[ "${ISTIO_AUTH_TYPE:-}" == "MUTUAL_TLS" ]]; then
  2473. setup-addon-manifests "addons" "istio/auth"
  2474. else
  2475. setup-addon-manifests "addons" "istio/noauth"
  2476. fi
  2477. fi
  2478. if [[ -n "${EXTRA_ADDONS_URL:-}" ]]; then
  2479. download-extra-addons
  2480. setup-addon-manifests "addons" "gce-extras"
  2481. fi
  2482. # Place addon manager pod manifest.
  2483. src_file="${src_dir}/kube-addon-manager.yaml"
  2484. sed -i -e "s@{{kubectl_extra_prune_whitelist}}@${ADDON_MANAGER_PRUNE_WHITELIST:-}@g" "${src_file}"
  2485. cp "${src_file}" /etc/kubernetes/manifests
  2486. }
  2487. function setup-node-termination-handler-manifest {
  2488. local -r nth_manifest="/etc/kubernetes/$1/$2/daemonset.yaml"
  2489. if [[ -n "${NODE_TERMINATION_HANDLER_IMAGE}" ]]; then
  2490. sed -i "s|image:.*|image: ${NODE_TERMINATION_HANDLER_IMAGE}|" "${nth_manifest}"
  2491. fi
  2492. }
  2493. # Setups manifests for ingress controller and gce-specific policies for service controller.
  2494. function start-lb-controller {
  2495. setup-addon-manifests "addons" "loadbalancing"
  2496. # Starts a l7 loadbalancing controller for ingress.
  2497. if [[ "${ENABLE_L7_LOADBALANCING:-}" == "glbc" ]]; then
  2498. echo "Start GCE L7 pod"
  2499. prepare-log-file /var/log/glbc.log
  2500. setup-addon-manifests "addons" "cluster-loadbalancing/glbc"
  2501. setup-addon-manifests "addons" "rbac/cluster-loadbalancing/glbc"
  2502. create-kubeconfig "l7-lb-controller" ${GCE_GLBC_TOKEN}
  2503. local -r src_manifest="${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/glbc.manifest"
  2504. local -r dest_manifest="/etc/kubernetes/manifests/glbc.manifest"
  2505. if [[ -n "${CUSTOM_INGRESS_YAML:-}" ]]; then
  2506. echo "${CUSTOM_INGRESS_YAML}" > "${dest_manifest}"
  2507. else
  2508. cp "${src_manifest}" "${dest_manifest}"
  2509. fi
  2510. # Override the glbc image if GCE_GLBC_IMAGE is specified.
  2511. if [[ -n "${GCE_GLBC_IMAGE:-}" ]]; then
  2512. sed -i "s|image:.*|image: ${GCE_GLBC_IMAGE}|" "${dest_manifest}"
  2513. fi
  2514. fi
  2515. }
  2516. # Setup working directory for kubelet.
  2517. function setup-kubelet-dir {
  2518. echo "Making /var/lib/kubelet executable for kubelet"
  2519. mount -B /var/lib/kubelet /var/lib/kubelet/
  2520. mount -B -o remount,exec,suid,dev /var/lib/kubelet
  2521. }
  2522. # Override for GKE custom master setup scripts (no-op outside of GKE).
  2523. function gke-master-start {
  2524. if [[ -e "${KUBE_HOME}/bin/gke-internal-configure-helper.sh" ]]; then
  2525. echo "Running GKE internal configuration script"
  2526. . "${KUBE_HOME}/bin/gke-internal-configure-helper.sh"
  2527. gke-internal-master-start
  2528. fi
  2529. }
  2530. function reset-motd {
  2531. # kubelet is installed both on the master and nodes, and the version is easy to parse (unlike kubectl)
  2532. local -r version="$("${KUBE_HOME}"/bin/kubelet --version=true | cut -f2 -d " ")"
  2533. # This logic grabs either a release tag (v1.2.1 or v1.2.1-alpha.1),
  2534. # or the git hash that's in the build info.
  2535. local gitref="$(echo "${version}" | sed -r "s/(v[0-9]+\.[0-9]+\.[0-9]+)(-[a-z]+\.[0-9]+)?.*/\1\2/g")"
  2536. local devel=""
  2537. if [[ "${gitref}" != "${version}" ]]; then
  2538. devel="
  2539. Note: This looks like a development version, which might not be present on GitHub.
  2540. If it isn't, the closest tag is at:
  2541. https://github.com/kubernetes/kubernetes/tree/${gitref}
  2542. "
  2543. gitref="${version//*+/}"
  2544. fi
  2545. cat > /etc/motd <<EOF
  2546. Welcome to Kubernetes ${version}!
  2547. You can find documentation for Kubernetes at:
  2548. http://docs.kubernetes.io/
  2549. The source for this release can be found at:
  2550. /home/kubernetes/kubernetes-src.tar.gz
  2551. Or you can download it at:
  2552. https://storage.googleapis.com/kubernetes-release/release/${version}/kubernetes-src.tar.gz
  2553. It is based on the Kubernetes source at:
  2554. https://github.com/kubernetes/kubernetes/tree/${gitref}
  2555. ${devel}
  2556. For Kubernetes copyright and licensing information, see:
  2557. /home/kubernetes/LICENSES
  2558. EOF
  2559. }
  2560. function override-kubectl {
  2561. echo "overriding kubectl"
  2562. echo "export PATH=${KUBE_HOME}/bin:\$PATH" > /etc/profile.d/kube_env.sh
  2563. # Add ${KUBE_HOME}/bin into sudoer secure path.
  2564. local sudo_path
  2565. sudo_path=$(sudo env | grep "^PATH=")
  2566. if [[ -n "${sudo_path}" ]]; then
  2567. sudo_path=${sudo_path#PATH=}
  2568. (
  2569. umask 027
  2570. echo "Defaults secure_path=\"${KUBE_HOME}/bin:${sudo_path}\"" > /etc/sudoers.d/kube_secure_path
  2571. )
  2572. fi
  2573. }
  2574. function override-pv-recycler {
  2575. if [[ -z "${PV_RECYCLER_OVERRIDE_TEMPLATE:-}" ]]; then
  2576. echo "PV_RECYCLER_OVERRIDE_TEMPLATE is not set"
  2577. exit 1
  2578. fi
  2579. PV_RECYCLER_VOLUME="{\"name\": \"pv-recycler-mount\",\"hostPath\": {\"path\": \"${PV_RECYCLER_OVERRIDE_TEMPLATE}\", \"type\": \"FileOrCreate\"}},"
  2580. PV_RECYCLER_MOUNT="{\"name\": \"pv-recycler-mount\",\"mountPath\": \"${PV_RECYCLER_OVERRIDE_TEMPLATE}\", \"readOnly\": true},"
  2581. cat > ${PV_RECYCLER_OVERRIDE_TEMPLATE} <<EOF
  2582. version: v1
  2583. kind: Pod
  2584. metadata:
  2585. generateName: pv-recycler-
  2586. namespace: default
  2587. spec:
  2588. activeDeadlineSeconds: 60
  2589. restartPolicy: Never
  2590. volumes:
  2591. - name: vol
  2592. containers:
  2593. - name: pv-recycler
  2594. image: k8s.gcr.io/busybox:1.27
  2595. command:
  2596. - /bin/sh
  2597. args:
  2598. - -c
  2599. - test -e /scrub && rm -rf /scrub/..?* /scrub/.[!.]* /scrub/* && test -z $(ls -A /scrub) || exit 1
  2600. volumeMounts:
  2601. - name: vol
  2602. mountPath: /scrub
  2603. EOF
  2604. }
  2605. function wait-till-apiserver-ready() {
  2606. until kubectl get nodes; do
  2607. sleep 5
  2608. done
  2609. }
  2610. function ensure-master-bootstrap-kubectl-auth {
  2611. # By default, `kubectl` uses http://localhost:8080
  2612. # If the insecure port is disabled, kubectl will need to use an admin-authenticated kubeconfig.
  2613. if [[ -n "${KUBE_BOOTSTRAP_TOKEN:-}" ]]; then
  2614. create-kubeconfig "kube-bootstrap" "${KUBE_BOOTSTRAP_TOKEN}"
  2615. export KUBECONFIG=/etc/srv/kubernetes/kube-bootstrap/kubeconfig
  2616. fi
  2617. }
  2618. function setup-containerd {
  2619. echo "Generate containerd config"
  2620. local config_path="${CONTAINERD_CONFIG_PATH:-"/etc/containerd/config.toml"}"
  2621. mkdir -p "$(dirname "${config_path}")"
  2622. local cni_template_path="${KUBE_HOME}/cni.template"
  2623. cat > "${cni_template_path}" <<EOF
  2624. {
  2625. "name": "k8s-pod-network",
  2626. "cniVersion": "0.3.1",
  2627. "plugins": [
  2628. {
  2629. "type": "ptp",
  2630. "mtu": 1460,
  2631. "ipam": {
  2632. "type": "host-local",
  2633. "subnet": "{{.PodCIDR}}",
  2634. "routes": [
  2635. {
  2636. "dst": "0.0.0.0/0"
  2637. }
  2638. ]
  2639. }
  2640. },
  2641. {
  2642. "type": "portmap",
  2643. "capabilities": {
  2644. "portMappings": true
  2645. }
  2646. }
  2647. ]
  2648. }
  2649. EOF
  2650. if [[ "${KUBERNETES_MASTER:-}" != "true" ]]; then
  2651. if [[ "${NETWORK_POLICY_PROVIDER:-"none"}" != "none" || "${ENABLE_NETD:-}" == "true" ]]; then
  2652. # Use Kubernetes cni daemonset on node if network policy provider is specified
  2653. # or netd is enabled.
  2654. cni_template_path=""
  2655. fi
  2656. fi
  2657. # Reuse docker group for containerd.
  2658. local containerd_gid="$(cat /etc/group | grep ^docker: | cut -d: -f 3)"
  2659. cat > "${config_path}" <<EOF
  2660. # Kubernetes doesn't use containerd restart manager.
  2661. disabled_plugins = ["restart"]
  2662. oom_score = -999
  2663. [debug]
  2664. level = "${CONTAINERD_LOG_LEVEL:-"info"}"
  2665. [grpc]
  2666. gid = ${containerd_gid}
  2667. [plugins.cri]
  2668. stream_server_address = "127.0.0.1"
  2669. max_container_log_line_size = ${CONTAINERD_MAX_CONTAINER_LOG_LINE:-262144}
  2670. [plugins.cri.cni]
  2671. bin_dir = "${KUBE_HOME}/bin"
  2672. conf_dir = "/etc/cni/net.d"
  2673. conf_template = "${cni_template_path}"
  2674. [plugins.cri.registry.mirrors."docker.io"]
  2675. endpoint = ["https://mirror.gcr.io","https://registry-1.docker.io"]
  2676. EOF
  2677. chmod 644 "${config_path}"
  2678. echo "Restart containerd to load the config change"
  2679. systemctl restart containerd
  2680. }
  2681. ########### Main Function ###########
  2682. function main() {
  2683. echo "Start to configure instance for kubernetes"
  2684. readonly UUID_MNT_PREFIX="/mnt/disks/by-uuid/google-local-ssds"
  2685. readonly UUID_BLOCK_PREFIX="/dev/disk/by-uuid/google-local-ssds"
  2686. readonly COREDNS_AUTOSCALER="Deployment/coredns"
  2687. readonly KUBEDNS_AUTOSCALER="Deployment/kube-dns"
  2688. # Resource requests of master components.
  2689. KUBE_CONTROLLER_MANAGER_CPU_REQUEST="${KUBE_CONTROLLER_MANAGER_CPU_REQUEST:-200m}"
  2690. KUBE_SCHEDULER_CPU_REQUEST="${KUBE_SCHEDULER_CPU_REQUEST:-75m}"
  2691. # Use --retry-connrefused opt only if it's supported by curl.
  2692. CURL_RETRY_CONNREFUSED=""
  2693. if curl --help | grep -q -- '--retry-connrefused'; then
  2694. CURL_RETRY_CONNREFUSED='--retry-connrefused'
  2695. fi
  2696. KUBE_HOME="/home/kubernetes"
  2697. CONTAINERIZED_MOUNTER_HOME="${KUBE_HOME}/containerized_mounter"
  2698. PV_RECYCLER_OVERRIDE_TEMPLATE="${KUBE_HOME}/kube-manifests/kubernetes/pv-recycler-template.yaml"
  2699. if [[ ! -e "${KUBE_HOME}/kube-env" ]]; then
  2700. echo "The ${KUBE_HOME}/kube-env file does not exist!! Terminate cluster initialization."
  2701. exit 1
  2702. fi
  2703. source "${KUBE_HOME}/kube-env"
  2704. if [[ -f "${KUBE_HOME}/kubelet-config.yaml" ]]; then
  2705. echo "Found Kubelet config file at ${KUBE_HOME}/kubelet-config.yaml"
  2706. KUBELET_CONFIG_FILE_ARG="--config ${KUBE_HOME}/kubelet-config.yaml"
  2707. fi
  2708. if [[ -e "${KUBE_HOME}/kube-master-certs" ]]; then
  2709. source "${KUBE_HOME}/kube-master-certs"
  2710. fi
  2711. if [[ -n "${KUBE_USER:-}" ]]; then
  2712. if ! [[ "${KUBE_USER}" =~ ^[-._@a-zA-Z0-9]+$ ]]; then
  2713. echo "Bad KUBE_USER format."
  2714. exit 1
  2715. fi
  2716. fi
  2717. KUBE_CONTROLLER_MANAGER_TOKEN="$(secure_random 32)"
  2718. KUBE_SCHEDULER_TOKEN="$(secure_random 32)"
  2719. KUBE_CLUSTER_AUTOSCALER_TOKEN="$(secure_random 32)"
  2720. if [[ "${ENABLE_L7_LOADBALANCING:-}" == "glbc" ]]; then
  2721. GCE_GLBC_TOKEN="$(secure_random 32)"
  2722. fi
  2723. ADDON_MANAGER_TOKEN="$(secure_random 32)"
  2724. if [[ "${ENABLE_APISERVER_INSECURE_PORT:-false}" != "true" ]]; then
  2725. KUBE_BOOTSTRAP_TOKEN="$(secure_random 32)"
  2726. fi
  2727. setup-os-params
  2728. config-ip-firewall
  2729. create-dirs
  2730. setup-kubelet-dir
  2731. ensure-local-ssds
  2732. setup-logrotate
  2733. if [[ "${KUBERNETES_MASTER:-}" == "true" ]]; then
  2734. mount-master-pd
  2735. create-node-pki
  2736. create-master-pki
  2737. create-master-auth
  2738. ensure-master-bootstrap-kubectl-auth
  2739. create-master-kubelet-auth
  2740. create-master-etcd-auth
  2741. create-master-etcd-apiserver-auth
  2742. override-pv-recycler
  2743. gke-master-start
  2744. else
  2745. create-node-pki
  2746. create-kubelet-kubeconfig ${KUBERNETES_MASTER_NAME}
  2747. if [[ "${KUBE_PROXY_DAEMONSET:-}" != "true" ]]; then
  2748. create-kubeproxy-user-kubeconfig
  2749. fi
  2750. if [[ "${ENABLE_NODE_PROBLEM_DETECTOR:-}" == "standalone" ]]; then
  2751. create-node-problem-detector-kubeconfig ${KUBERNETES_MASTER_NAME}
  2752. fi
  2753. fi
  2754. override-kubectl
  2755. container_runtime="${CONTAINER_RUNTIME:-docker}"
  2756. # Run the containerized mounter once to pre-cache the container image.
  2757. if [[ "${container_runtime}" == "docker" ]]; then
  2758. assemble-docker-flags
  2759. elif [[ "${container_runtime}" == "containerd" ]]; then
  2760. setup-containerd
  2761. fi
  2762. start-kubelet
  2763. if [[ "${KUBERNETES_MASTER:-}" == "true" ]]; then
  2764. compute-master-manifest-variables
  2765. if [[ -z "${ETCD_SERVERS:-}" ]]; then
  2766. start-etcd-servers
  2767. start-etcd-empty-dir-cleanup-pod
  2768. fi
  2769. start-kube-apiserver
  2770. start-kube-controller-manager
  2771. start-kube-scheduler
  2772. wait-till-apiserver-ready
  2773. start-kube-addons
  2774. start-cluster-autoscaler
  2775. start-lb-controller
  2776. update-legacy-addon-node-labels &
  2777. apply-encryption-config &
  2778. else
  2779. if [[ "${KUBE_PROXY_DAEMONSET:-}" != "true" ]]; then
  2780. start-kube-proxy
  2781. fi
  2782. if [[ "${ENABLE_NODE_PROBLEM_DETECTOR:-}" == "standalone" ]]; then
  2783. start-node-problem-detector
  2784. fi
  2785. fi
  2786. reset-motd
  2787. prepare-mounter-rootfs
  2788. modprobe configs
  2789. echo "Done for the configuration for kubernetes"
  2790. }
  2791. if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  2792. main "${@}"
  2793. fi