02k8s-install-centos.sh 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863
  1. #!/usr/bin/env bash
  2. # 参考 https://raw.githubusercontent.com/lework/kainstall/v1.4.9/kainstall-centos.sh
  3. [[ -n $DEBUG ]] && set -x
  4. set -o errtrace # Make sure any error trap is inherited
  5. set -o nounset # Disallow expansion of unset variables
  6. set -o pipefail # Use last non-zero exit code in a pipeline
  7. # 版本
  8. KUBE_VERSION="${KUBE_VERSION:-latest}"
  9. FLANNEL_VERSION="${FLANNEL_VERSION:-0.17.0}"
  10. CALICO_VERSION="${CALICO_VERSION:-3.22.1}"
  11. CILIUM_VERSION="${CILIUM_VERSION:-1.9.13}"
  12. HELM_VERSION="${HELM_VERSION:-3.10.1}"
  13. INGRESS_NGINX="${INGRESS_NGINX:-4.2.5}"
  14. RANCHER_VERSION="${RANCHER_VERSION:-2.6.9}"
  15. #METRICS_SERVER_VERSION="${METRICS_SERVER_VERSION:-0.6.1}"
  16. #KUBE_PROMETHEUS_VERSION="${KUBE_PROMETHEUS_VERSION:-0.10.0}"
  17. #ELASTICSEARCH_VERSION="${ELASTICSEARCH_VERSION:-8.1.0}"
  18. #ROOK_VERSION="${ROOK_VERSION:-1.8.7}"
  19. #LONGHORN_VERSION="${LONGHORN_VERSION:-1.2.4}"
  20. # 集群配置
  21. KUBE_DNSDOMAIN="${KUBE_DNSDOMAIN:-cluster.local}"
  22. KUBE_APISERVER="${KUBE_APISERVER:-apiserver.$KUBE_DNSDOMAIN}"
  23. KUBE_POD_SUBNET="${KUBE_POD_SUBNET:-10.244.0.0/16}"
  24. KUBE_SERVICE_SUBNET="${KUBE_SERVICE_SUBNET:-10.96.0.0/16}"
  25. KUBE_IMAGE_REPO="${KUBE_IMAGE_REPO:-registry.cn-hangzhou.aliyuncs.com/kainstall}"
  26. KUBE_NETWORK="${KUBE_NETWORK:-flannel}"
  27. KUBE_INGRESS="${KUBE_INGRESS:-nginx}"
  28. KUBE_MONITOR="${KUBE_MONITOR:-prometheus}"
  29. KUBE_STORAGE="${KUBE_STORAGE:-rook}"
  30. KUBE_LOG="${KUBE_LOG:-elasticsearch}"
  31. KUBE_FLANNEL_TYPE="${KUBE_FLANNEL_TYPE:-vxlan}"
  32. KUBE_CRI="${KUBE_CRI:-docker}"
  33. KUBE_CRI_VERSION="${KUBE_CRI_VERSION:-latest}"
  34. KUBE_CRI_ENDPOINT="${KUBE_CRI_ENDPOINT:-/var/run/dockershim.sock}"
  35. # 定义的master和worker节点地址,以逗号分隔
  36. MASTER_NODES="${MASTER_NODES:-}"
  37. WORKER_NODES="${WORKER_NODES:-}"
  38. # 定义在哪个节点上进行设置
  39. MGMT_NODE="${MGMT_NODE:-127.0.0.1}"
  40. # 节点的连接信息
  41. SSH_USER="${SSH_USER:-root}"
  42. SSH_PASSWORD="${SSH_PASSWORD:-}"
  43. SSH_PRIVATE_KEY="${SSH_PRIVATE_KEY:-}"
  44. SSH_PORT="${SSH_PORT:-22}"
  45. SUDO_USER="${SUDO_USER:-root}"
  46. # 节点设置
  47. HOSTNAME_PREFIX="${HOSTNAME_PREFIX:-k8s}"
  48. # nginx的端口配置
  49. NGINX_HTTP_PORT="${NGINX_HTTP_PORT:-80}"
  50. # 脚本设置
  51. TMP_DIR="$(rm -rf /tmp/kainstall* && mktemp -d -t kainstall.XXXXXXXXXX)"
  52. LOG_FILE="${TMP_DIR}/kainstall.log"
  53. SSH_OPTIONS="-o ConnectTimeout=600 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
  54. ERROR_INFO="\n\033[31mERROR Summary: \033[0m\n "
  55. ACCESS_INFO="\n\033[32mACCESS Summary: \033[0m\n "
  56. COMMAND_OUTPUT=""
  57. SCRIPT_PARAMETER="$*"
  58. OFFLINE_DIR="/tmp/kainstall-offline-file/"
  59. OFFLINE_FILE=""
  60. OS_SUPPORT="centos7 centos8 rocky8.7"
  61. GITHUB_PROXY="${GITHUB_PROXY:-https://ghproxy.com/}"
  62. GCR_PROXY="${GCR_PROXY:-k8sgcr.lework.workers.dev}"
  63. SKIP_UPGRADE_PLAN=${SKIP_UPGRADE_PLAN:-false}
  64. SKIP_SET_OS_REPO=${SKIP_SET_OS_REPO:-false}
  65. trap trap::info 1 2 3 15 EXIT
  66. ######################################################################################################
  67. # 通用函数
  68. ######################################################################################################
  69. # 信号处理
  70. function trap::info() {
  71. [[ ${#ERROR_INFO} -gt 37 ]] && echo -e "$ERROR_INFO"
  72. [[ ${#ACCESS_INFO} -gt 38 ]] && echo -e "$ACCESS_INFO"
  73. [ -f "$LOG_FILE" ] && echo -e "\n\n See detailed log >>> $LOG_FILE \n\n"
  74. trap '' EXIT
  75. exit
  76. }
  77. # 错误日志
  78. function log::error() {
  79. local item; item="[$(date +'%Y-%m-%dT%H:%M:%S.%N%z')]: \033[31mERROR: \033[0m$*"
  80. ERROR_INFO="${ERROR_INFO}${item}\n "
  81. echo -e "${item}" | tee -a "$LOG_FILE"
  82. }
  83. # 基础日志
  84. function log::info() {
  85. printf "[%s]: \033[32mINFO: \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" | tee -a "$LOG_FILE"
  86. }
  87. # 警告日志
  88. function log::warning() {
  89. printf "[%s]: \033[33mWARNING: \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" | tee -a "$LOG_FILE"
  90. }
  91. # 访问信息
  92. function log::access() {
  93. ACCESS_INFO="${ACCESS_INFO}$*\n "
  94. printf "[%s]: \033[32mINFO: \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" | tee -a "$LOG_FILE"
  95. }
  96. # 执行日志
  97. function log::exec() {
  98. printf "[%s]: \033[34mEXEC: \033[0m%s\n" "$(date +'%Y-%m-%dT%H:%M:%S.%N%z')" "$*" >> "$LOG_FILE"
  99. }
  100. # 版本号转数字
  101. function utils::version_to_number() {
  102. echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }';
  103. }
  104. # 重试
  105. function utils::retry() {
  106. local retries=$1
  107. shift
  108. local count=0
  109. until eval "$*"; do
  110. exit=$?
  111. wait=$((2 ** count))
  112. count=$((count + 1))
  113. if [ "$count" -lt "$retries" ]; then
  114. echo "Retry $count/$retries exited $exit, retrying in $wait seconds..."
  115. sleep $wait
  116. else
  117. echo "Retry $count/$retries exited $exit, no more retries left."
  118. return $exit
  119. fi
  120. done
  121. return 0
  122. }
  123. # 转义引号
  124. function utils::quote() {
  125. # shellcheck disable=SC2046
  126. if [ $(echo "$*" | tr -d "\n" | wc -c) -eq 0 ]; then
  127. echo "''"
  128. elif [ $(echo "$*" | tr -d "[a-z][A-Z][0-9]:,.=~_/\n-" | wc -c) -gt 0 ]; then
  129. printf "%s" "$*" | sed -e "1h;2,\$H;\$!d;g" -e "s/'/\'\"\'\"\'/g" | sed -e "1h;2,\$H;\$!d;g" -e "s/^/'/g" -e "s/$/'/g"
  130. else
  131. echo "$*"
  132. fi
  133. }
  134. # 下载文件
  135. function utils::download_file() {
  136. local url="$1"
  137. local dest="$2"
  138. local unzip_tag="${3:-1}"
  139. local dest_dirname; dest_dirname=$(dirname "$dest")
  140. local filename; filename=$(basename "$dest")
  141. log::info "[download]" "${filename}"
  142. command::exec "${MGMT_NODE}" "
  143. set -e
  144. if [ ! -f \"${dest}\" ]; then
  145. [ ! -d \"${dest_dirname}\" ] && mkdir -pv \"${dest_dirname}\"
  146. wget --timeout=10 --waitretry=3 --tries=5 --retry-connrefused --no-check-certificate \"${url}\" -O \"${dest}\"
  147. if [[ \"${unzip_tag}\" == \"unzip\" ]]; then
  148. command -v unzip 2>/dev/null || yum install -y unzip
  149. unzip -o \"${dest}\" -d \"${dest_dirname}\"
  150. fi
  151. else
  152. echo \"${dest} is exists!\"
  153. fi
  154. "
  155. local status="$?"
  156. check::exit_code "$status" "download" "${filename}" "exit"
  157. return "$status"
  158. }
  159. # 判断是否在数组中存在元素
  160. function utils::is_element_in_array() {
  161. local -r element="${1}"
  162. local -r array=("${@:2}")
  163. local walker=''
  164. for walker in "${array[@]}"
  165. do
  166. [[ "${walker}" = "${element}" ]] && return 0
  167. done
  168. return 1
  169. }
  170. # 执行命令
  171. function command::exec() {
  172. local host=${1:-}
  173. shift
  174. local command="$*"
  175. if [[ "${SUDO_TAG:-}" == "1" ]]; then
  176. sudo_options="sudo -H -n -u ${SUDO_USER}"
  177. if [[ "${SUDO_PASSWORD:-}" != "" ]]; then
  178. sudo_options="${sudo_options// -n/} -p \"\" -S <<< \"${SUDO_PASSWORD}\""
  179. fi
  180. command="$sudo_options bash -c $(utils::quote "$command")"
  181. fi
  182. command="$(utils::quote "$command")"
  183. if [[ "${host}" == "127.0.0.1" || "${host}" == "10.0.93.197" ]]; then
  184. # 本地执行
  185. log::exec "[command]" "bash -c $(printf "%s" "${command//${SUDO_PASSWORD:-}/zzzzzz}")"
  186. # shellcheck disable=SC2094
  187. COMMAND_OUTPUT=$(eval bash -c "${command}" 2>> "$LOG_FILE" | tee -a "$LOG_FILE")
  188. local status=$?
  189. else
  190. # 远程执行
  191. local ssh_cmd="ssh"
  192. if [[ "${SSH_PASSWORD}" != "" ]]; then
  193. ssh_cmd="sshpass -p \"${SSH_PASSWORD}\" ${ssh_cmd}"
  194. elif [[ "$SSH_PRIVATE_KEY" != "" ]]; then
  195. [ -f "${SSH_PRIVATE_KEY}" ] || { log::error "[exec]" "ssh private_key:${SSH_PRIVATE_KEY} not found."; exit 1; }
  196. ssh_cmd="${ssh_cmd} -i $SSH_PRIVATE_KEY"
  197. fi
  198. log::exec "[command]" "${ssh_cmd//${SSH_PASSWORD:-}/zzzzzz} ${SSH_OPTIONS} ${SSH_USER}@${host} -p ${SSH_PORT} bash -c $(printf "%s" "${command//${SUDO_PASSWORD:-}/zzzzzz}")"
  199. # shellcheck disable=SC2094
  200. COMMAND_OUTPUT=$(eval "${ssh_cmd} ${SSH_OPTIONS} ${SSH_USER}@${host} -p ${SSH_PORT}" bash -c '"${command}"' 2>> "$LOG_FILE" | tee -a "$LOG_FILE")
  201. local status=$?
  202. fi
  203. return $status
  204. }
  205. # 拷贝文件
  206. function command::scp() {
  207. local host=${1:-}
  208. local src=${2:-}
  209. local dest=${3:-/tmp/}
  210. if [[ "${host}" == "127.0.0.1" ]]; then
  211. local command="cp -rf ${src} ${dest}"
  212. log::exec "[command]" "bash -c \"${command}\""
  213. # shellcheck disable=SC2094
  214. COMMAND_OUTPUT=$(bash -c "${command}" 2>> "$LOG_FILE" | tee -a "$LOG_FILE")
  215. local status=$?
  216. else
  217. local scp_cmd="scp"
  218. if [[ "${SSH_PASSWORD}" != "" ]]; then
  219. scp_cmd="sshpass -p \"${SSH_PASSWORD}\" ${scp_cmd}"
  220. elif [[ "$SSH_PRIVATE_KEY" != "" ]]; then
  221. [ -f "${SSH_PRIVATE_KEY}" ] || { log::error "[exec]" "ssh private_key:${SSH_PRIVATE_KEY} not found."; exit 1; }
  222. scp_cmd="${scp_cmd} -i $SSH_PRIVATE_KEY"
  223. fi
  224. log::exec "[command]" "${scp_cmd} ${SSH_OPTIONS} -P ${SSH_PORT} -r ${src} ${SSH_USER}@${host}:${dest}" >> "$LOG_FILE"
  225. # shellcheck disable=SC2094
  226. COMMAND_OUTPUT=$(eval "${scp_cmd} ${SSH_OPTIONS} -P ${SSH_PORT} -r ${src} ${SSH_USER}@${host}:${dest}" 2>> "$LOG_FILE" | tee -a "$LOG_FILE")
  227. local status=$?
  228. fi
  229. return $status
  230. }
  231. # 检查命令是否存在
  232. function check::command_exists() {
  233. local cmd=${1}
  234. local package=${2}
  235. if command -V "$cmd" > /dev/null 2>&1; then
  236. log::info "[check]" "$cmd command exists."
  237. else
  238. log::warning "[check]" "I require $cmd but it's not installed."
  239. log::warning "[check]" "install $package package."
  240. command::exec "127.0.0.1" "yum install -y ${package}"
  241. check::exit_code "$?" "check" "$package install" "exit"
  242. fi
  243. }
  244. ######################################################################################################
  245. # 安装函数
  246. ######################################################################################################
  247. # 节点初始化脚本
  248. function script::init_node() {
  249. # clean
  250. sed -i -e "/$KUBE_APISERVER/d" -e '/-worker-/d' -e '/-master-/d' /etc/hosts
  251. sed -i '/## Kainstall managed start/,/## Kainstall managed end/d' /etc/security/limits.conf /etc/systemd/system.conf /etc/bashrc /etc/rc.local /etc/audit/rules.d/audit.rules
  252. # Disable selinux
  253. sed -i '/SELINUX/s/enforcing/disabled/' /etc/selinux/config
  254. setenforce 0
  255. # Disable swap
  256. swapoff -a && sysctl -w vm.swappiness=0
  257. sed -ri '/^[^#]*swap/s@^@#@' /etc/fstab
  258. # Disable firewalld
  259. for target in firewalld python-firewall firewalld-filesystem iptables; do
  260. systemctl stop $target &>/dev/null || true
  261. systemctl disable $target &>/dev/null || true
  262. done
  263. # repo
  264. [[ -f /etc/yum.repos.d/CentOS-Base.repo && "${SKIP_SET_OS_REPO,,}" == "false" ]] && sed -e 's!^#baseurl=!baseurl=!g' \
  265. -e 's!^mirrorlist=!#mirrorlist=!g' \
  266. -e 's!mirror.centos.org!mirrors.aliyun.com!g' \
  267. -i /etc/yum.repos.d/CentOS-Base.repo
  268. [[ "${OFFLINE_TAG:-}" != "1" && "${SKIP_SET_OS_REPO,,}" == "false" ]] && yum install -y epel-release
  269. [[ -f /etc/yum.repos.d/epel.repo && "${SKIP_SET_OS_REPO,,}" == "false" ]] && sed -e 's!^mirrorlist=!#mirrorlist=!g' \
  270. -e 's!^metalink=!#metalink=!g' \
  271. -e 's!^#baseurl=!baseurl=!g' \
  272. -e 's!//download.*/pub!//mirrors.aliyun.com!g' \
  273. -e 's!http://mirrors\.aliyun!https://mirrors.aliyun!g' \
  274. -i /etc/yum.repos.d/epel.repo
  275. # Change limits
  276. [ ! -f /etc/security/limits.conf_bak ] && cp /etc/security/limits.conf{,_bak}
  277. cat << EOF >> /etc/security/limits.conf
  278. ## Kainstall managed start
  279. root soft nofile 655360
  280. root hard nofile 655360
  281. root soft nproc 655360
  282. root hard nproc 655360
  283. root soft core unlimited
  284. root hard core unlimited
  285. * soft nofile 655360
  286. * hard nofile 655360
  287. * soft nproc 655360
  288. * hard nproc 655360
  289. * soft core unlimited
  290. * hard core unlimited
  291. ## Kainstall managed end
  292. EOF
  293. # /etc/systemd/system.conf
  294. [ -f /etc/security/limits.d/20-nproc.conf ] && sed -i 's#4096#655360#g' /etc/security/limits.d/20-nproc.conf
  295. cat << EOF >> /etc/systemd/system.conf
  296. ## Kainstall managed start
  297. DefaultLimitCORE=infinity
  298. DefaultLimitNOFILE=655360
  299. DefaultLimitNPROC=655360
  300. DefaultTasksMax=75%
  301. ## Kainstall managed end
  302. EOF
  303. # Change sysctl
  304. cat << EOF > /etc/sysctl.d/99-kube.conf
  305. # https://www.kernel.org/doc/Documentation/sysctl/
  306. #############################################################################################
  307. # 调整虚拟内存
  308. #############################################################################################
  309. # Default: 30
  310. # 0 - 任何情况下都不使用swap。
  311. # 1 - 除非内存不足(OOM),否则不使用swap。
  312. vm.swappiness = 0
  313. # 内存分配策略
  314. #0 - 表示内核将检查是否有足够的可用内存供应用进程使用;如果有足够的可用内存,内存申请允许;否则,内存申请失败,并把错误返回给应用进程。
  315. #1 - 表示内核允许分配所有的物理内存,而不管当前的内存状态如何。
  316. #2 - 表示内核允许分配超过所有物理内存和交换空间总和的内存
  317. vm.overcommit_memory=1
  318. # OOM时处理
  319. # 1关闭,等于0时,表示当内存耗尽时,内核会触发OOM killer杀掉最耗内存的进程。
  320. vm.panic_on_oom=0
  321. # vm.dirty_background_ratio 用于调整内核如何处理必须刷新到磁盘的脏页。
  322. # Default value is 10.
  323. # 该值是系统内存总量的百分比,在许多情况下将此值设置为5是合适的。
  324. # 此设置不应设置为零。
  325. vm.dirty_background_ratio = 5
  326. # 内核强制同步操作将其刷新到磁盘之前允许的脏页总数
  327. # 也可以通过更改 vm.dirty_ratio 的值(将其增加到默认值30以上(也占系统内存的百分比))来增加
  328. # 推荐 vm.dirty_ratio 的值在60到80之间。
  329. vm.dirty_ratio = 60
  330. # vm.max_map_count 计算当前的内存映射文件数。
  331. # mmap 限制(vm.max_map_count)的最小值是打开文件的ulimit数量(cat /proc/sys/fs/file-max)。
  332. # 每128KB系统内存 map_count应该大约为1。 因此,在32GB系统上,max_map_count为262144。
  333. # Default: 65530
  334. vm.max_map_count = 2097152
  335. #############################################################################################
  336. # 调整文件
  337. #############################################################################################
  338. fs.may_detach_mounts = 1
  339. # 增加文件句柄和inode缓存的大小,并限制核心转储。
  340. fs.file-max = 2097152
  341. fs.nr_open = 2097152
  342. fs.suid_dumpable = 0
  343. # 文件监控
  344. fs.inotify.max_user_instances=8192
  345. fs.inotify.max_user_watches=524288
  346. fs.inotify.max_queued_events=16384
  347. #############################################################################################
  348. # 调整网络设置
  349. #############################################################################################
  350. # 为每个套接字的发送和接收缓冲区分配的默认内存量。
  351. net.core.wmem_default = 25165824
  352. net.core.rmem_default = 25165824
  353. # 为每个套接字的发送和接收缓冲区分配的最大内存量。
  354. net.core.wmem_max = 25165824
  355. net.core.rmem_max = 25165824
  356. # 除了套接字设置外,发送和接收缓冲区的大小
  357. # 必须使用net.ipv4.tcp_wmem和net.ipv4.tcp_rmem参数分别设置TCP套接字。
  358. # 使用三个以空格分隔的整数设置这些整数,分别指定最小,默认和最大大小。
  359. # 最大大小不能大于使用net.core.wmem_max和net.core.rmem_max为所有套接字指定的值。
  360. # 合理的设置是最小4KiB,默认64KiB和最大2MiB缓冲区。
  361. net.ipv4.tcp_wmem = 20480 12582912 25165824
  362. net.ipv4.tcp_rmem = 20480 12582912 25165824
  363. # 增加最大可分配的总缓冲区空间
  364. # 以页为单位(4096字节)进行度量
  365. net.ipv4.tcp_mem = 65536 25165824 262144
  366. net.ipv4.udp_mem = 65536 25165824 262144
  367. # 为每个套接字的发送和接收缓冲区分配的最小内存量。
  368. net.ipv4.udp_wmem_min = 16384
  369. net.ipv4.udp_rmem_min = 16384
  370. # 启用TCP窗口缩放,客户端可以更有效地传输数据,并允许在代理方缓冲该数据。
  371. net.ipv4.tcp_window_scaling = 1
  372. # 提高同时接受连接数。
  373. net.ipv4.tcp_max_syn_backlog = 10240
  374. # 将net.core.netdev_max_backlog的值增加到大于默认值1000
  375. # 可以帮助突发网络流量,特别是在使用数千兆位网络连接速度时,
  376. # 通过允许更多的数据包排队等待内核处理它们。
  377. net.core.netdev_max_backlog = 65536
  378. # 增加选项内存缓冲区的最大数量
  379. net.core.optmem_max = 25165824
  380. # 被动TCP连接的SYNACK次数。
  381. net.ipv4.tcp_synack_retries = 2
  382. # 允许的本地端口范围。
  383. net.ipv4.ip_local_port_range = 2048 65535
  384. # 防止TCP时间等待
  385. # Default: net.ipv4.tcp_rfc1337 = 0
  386. net.ipv4.tcp_rfc1337 = 1
  387. # 减少tcp_fin_timeout连接的时间默认值
  388. net.ipv4.tcp_fin_timeout = 15
  389. # 积压套接字的最大数量。
  390. # Default is 128.
  391. net.core.somaxconn = 32768
  392. # 打开syncookies以进行SYN洪水攻击保护。
  393. net.ipv4.tcp_syncookies = 1
  394. # 避免Smurf攻击
  395. # 发送伪装的ICMP数据包,目的地址设为某个网络的广播地址,源地址设为要攻击的目的主机,
  396. # 使所有收到此ICMP数据包的主机都将对目的主机发出一个回应,使被攻击主机在某一段时间内收到成千上万的数据包
  397. net.ipv4.icmp_echo_ignore_broadcasts = 1
  398. # 为icmp错误消息打开保护
  399. net.ipv4.icmp_ignore_bogus_error_responses = 1
  400. # 启用自动缩放窗口。
  401. # 如果延迟证明合理,这将允许TCP缓冲区超过其通常的最大值64K。
  402. net.ipv4.tcp_window_scaling = 1
  403. # 打开并记录欺骗,源路由和重定向数据包
  404. net.ipv4.conf.all.log_martians = 1
  405. net.ipv4.conf.default.log_martians = 1
  406. # 告诉内核有多少个未附加的TCP套接字维护用户文件句柄。 万一超过这个数字,
  407. # 孤立的连接会立即重置,并显示警告。
  408. # Default: net.ipv4.tcp_max_orphans = 65536
  409. net.ipv4.tcp_max_orphans = 65536
  410. # 不要在关闭连接时缓存指标
  411. net.ipv4.tcp_no_metrics_save = 1
  412. # 启用RFC1323中定义的时间戳记:
  413. # Default: net.ipv4.tcp_timestamps = 1
  414. net.ipv4.tcp_timestamps = 1
  415. # 启用选择确认。
  416. # Default: net.ipv4.tcp_sack = 1
  417. net.ipv4.tcp_sack = 1
  418. # 增加 tcp-time-wait 存储桶池大小,以防止简单的DOS攻击。
  419. # net.ipv4.tcp_tw_recycle 已从Linux 4.12中删除。请改用net.ipv4.tcp_tw_reuse。
  420. net.ipv4.tcp_max_tw_buckets = 14400
  421. net.ipv4.tcp_tw_reuse = 1
  422. # accept_source_route 选项使网络接口接受设置了严格源路由(SSR)或松散源路由(LSR)选项的数据包。
  423. # 以下设置将丢弃设置了SSR或LSR选项的数据包。
  424. net.ipv4.conf.all.accept_source_route = 0
  425. net.ipv4.conf.default.accept_source_route = 0
  426. # 打开反向路径过滤
  427. net.ipv4.conf.all.rp_filter = 1
  428. net.ipv4.conf.default.rp_filter = 1
  429. # 禁用ICMP重定向接受
  430. net.ipv4.conf.all.accept_redirects = 0
  431. net.ipv4.conf.default.accept_redirects = 0
  432. net.ipv4.conf.all.secure_redirects = 0
  433. net.ipv4.conf.default.secure_redirects = 0
  434. # 禁止发送所有IPv4 ICMP重定向数据包。
  435. net.ipv4.conf.all.send_redirects = 0
  436. net.ipv4.conf.default.send_redirects = 0
  437. # 开启IP转发.
  438. net.ipv4.ip_forward = 1
  439. # 禁止IPv6
  440. net.ipv6.conf.lo.disable_ipv6=1
  441. net.ipv6.conf.all.disable_ipv6 = 1
  442. net.ipv6.conf.default.disable_ipv6 = 1
  443. # 要求iptables不对bridge的数据进行处理
  444. net.bridge.bridge-nf-call-ip6tables = 1
  445. net.bridge.bridge-nf-call-iptables = 1
  446. net.bridge.bridge-nf-call-arptables = 1
  447. # arp缓存
  448. # 存在于 ARP 高速缓存中的最少层数,如果少于这个数,垃圾收集器将不会运行。缺省值是 128
  449. net.ipv4.neigh.default.gc_thresh1=2048
  450. # 保存在 ARP 高速缓存中的最多的记录软限制。垃圾收集器在开始收集前,允许记录数超过这个数字 5 秒。缺省值是 512
  451. net.ipv4.neigh.default.gc_thresh2=4096
  452. # 保存在 ARP 高速缓存中的最多记录的硬限制,一旦高速缓存中的数目高于此,垃圾收集器将马上运行。缺省值是 1024
  453. net.ipv4.neigh.default.gc_thresh3=8192
  454. # 持久连接
  455. net.ipv4.tcp_keepalive_time = 600
  456. net.ipv4.tcp_keepalive_intvl = 30
  457. net.ipv4.tcp_keepalive_probes = 10
  458. # conntrack表
  459. net.nf_conntrack_max=1048576
  460. net.netfilter.nf_conntrack_max=1048576
  461. net.netfilter.nf_conntrack_buckets=262144
  462. net.netfilter.nf_conntrack_tcp_timeout_fin_wait=30
  463. net.netfilter.nf_conntrack_tcp_timeout_time_wait=30
  464. net.netfilter.nf_conntrack_tcp_timeout_close_wait=15
  465. net.netfilter.nf_conntrack_tcp_timeout_established=300
  466. #############################################################################################
  467. # 调整内核参数
  468. #############################################################################################
  469. # 地址空间布局随机化(ASLR)是一种用于操作系统的内存保护过程,可防止缓冲区溢出攻击。
  470. # 这有助于确保与系统上正在运行的进程相关联的内存地址不可预测,
  471. # 因此,与这些流程相关的缺陷或漏洞将更加难以利用。
  472. # Accepted values: 0 = 关闭, 1 = 保守随机化, 2 = 完全随机化
  473. kernel.randomize_va_space = 2
  474. # 调高 PID 数量
  475. kernel.pid_max = 65536
  476. kernel.threads-max=30938
  477. # coredump
  478. kernel.core_pattern=core
  479. # 决定了检测到soft lockup时是否自动panic,缺省值是0
  480. kernel.softlockup_all_cpu_backtrace=1
  481. kernel.softlockup_panic=1
  482. EOF
  483. # history
  484. cat << EOF >> /etc/bashrc
  485. ## Kainstall managed start
  486. # history actions record,include action time, user, login ip
  487. HISTFILESIZE=5000
  488. HISTSIZE=5000
  489. USER_IP=\$(who -u am i 2>/dev/null | awk '{print \$NF}' | sed -e 's/[()]//g')
  490. if [ -z \$USER_IP ]
  491. then
  492. USER_IP=\$(hostname -i)
  493. fi
  494. HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S \$USER_IP:\$(whoami) "
  495. export HISTFILESIZE HISTSIZE HISTTIMEFORMAT
  496. # PS1
  497. PS1='\[\033[0m\]\[\033[1;36m\][\u\[\033[0m\]@\[\033[1;32m\]\h\[\033[0m\] \[\033[1;31m\]\w\[\033[0m\]\[\033[1;36m\]]\[\033[33;1m\]\\$ \[\033[0m\]'
  498. ## Kainstall managed end
  499. EOF
  500. # journal
  501. mkdir -p /var/log/journal /etc/systemd/journald.conf.d
  502. cat << EOF > /etc/systemd/journald.conf.d/99-prophet.conf
  503. [Journal]
  504. # 持久化保存到磁盘
  505. Storage=persistent
  506. # 压缩历史日志
  507. Compress=yes
  508. SyncIntervalSec=5m
  509. RateLimitInterval=30s
  510. RateLimitBurst=1000
  511. # 最大占用空间 2G
  512. SystemMaxUse=2G
  513. # 单日志文件最大 100M
  514. SystemMaxFileSize=100M
  515. # 日志保存时间 3 周
  516. MaxRetentionSec=3week
  517. # 不将日志转发到 syslog
  518. ForwardToSyslog=no
  519. EOF
  520. # motd
  521. cat << EOF > /etc/profile.d/zz-ssh-login-info.sh
  522. #!/bin/sh
  523. #
  524. # @Time : 2020-02-04
  525. # @Author : lework
  526. # @Desc : ssh login banner
  527. export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:\$PATH
  528. #shopt -q login_shell && : || return 0
  529. # os
  530. upSeconds="\$(cut -d. -f1 /proc/uptime)"
  531. secs=\$((\${upSeconds}%60))
  532. mins=\$((\${upSeconds}/60%60))
  533. hours=\$((\${upSeconds}/3600%24))
  534. days=\$((\${upSeconds}/86400))
  535. UPTIME_INFO=\$(printf "%d days, %02dh %02dm %02ds" "\$days" "\$hours" "\$mins" "\$secs")
  536. if [ -f /etc/redhat-release ] ; then
  537. PRETTY_NAME=\$(< /etc/redhat-release)
  538. elif [ -f /etc/debian_version ]; then
  539. DIST_VER=\$(</etc/debian_version)
  540. PRETTY_NAME="\$(grep PRETTY_NAME /etc/os-release | sed -e 's/PRETTY_NAME=//g' -e 's/"//g') (\$DIST_VER)"
  541. else
  542. PRETTY_NAME=\$(cat /etc/*-release | grep "PRETTY_NAME" | sed -e 's/PRETTY_NAME=//g' -e 's/"//g')
  543. fi
  544. if [[ -d "/system/app/" && -d "/system/priv-app" ]]; then
  545. model="\$(getprop ro.product.brand) \$(getprop ro.product.model)"
  546. elif [[ -f /sys/devices/virtual/dmi/id/product_name ||
  547. -f /sys/devices/virtual/dmi/id/product_version ]]; then
  548. model="\$(< /sys/devices/virtual/dmi/id/product_name)"
  549. model+=" \$(< /sys/devices/virtual/dmi/id/product_version)"
  550. elif [[ -f /sys/firmware/devicetree/base/model ]]; then
  551. model="\$(< /sys/firmware/devicetree/base/model)"
  552. elif [[ -f /tmp/sysinfo/model ]]; then
  553. model="\$(< /tmp/sysinfo/model)"
  554. fi
  555. MODEL_INFO=\${model}
  556. KERNEL=\$(uname -srmo)
  557. USER_NUM=\$(who -u | wc -l)
  558. RUNNING=\$(ps ax | wc -l | tr -d " ")
  559. # disk
  560. totaldisk=\$(df -h -x devtmpfs -x tmpfs -x debugfs -x aufs -x overlay --total 2>/dev/null | tail -1)
  561. disktotal=\$(awk '{print \$2}' <<< "\${totaldisk}")
  562. diskused=\$(awk '{print \$3}' <<< "\${totaldisk}")
  563. diskusedper=\$(awk '{print \$5}' <<< "\${totaldisk}")
  564. DISK_INFO="\033[0;33m\${diskused}\033[0m of \033[1;34m\${disktotal}\033[0m disk space used (\033[0;33m\${diskusedper}\033[0m)"
  565. # cpu
  566. cpu=\$(awk -F':' '/^model name/ {print \$2}' /proc/cpuinfo | uniq | sed -e 's/^[ \t]*//')
  567. cpun=\$(grep -c '^processor' /proc/cpuinfo)
  568. cpuc=\$(grep '^cpu cores' /proc/cpuinfo | tail -1 | awk '{print \$4}')
  569. cpup=\$(grep '^physical id' /proc/cpuinfo | wc -l)
  570. CPU_INFO="\${cpu} \${cpup}P \${cpuc}C \${cpun}L"
  571. # get the load averages
  572. read one five fifteen rest < /proc/loadavg
  573. LOADAVG_INFO="\033[0;33m\${one}\033[0m / \${five} / \${fifteen} with \033[1;34m\$(( cpun*cpuc ))\033[0m core(s) at \033[1;34m\$(grep '^cpu MHz' /proc/cpuinfo | tail -1 | awk '{print \$4}')\033 MHz"
  574. # mem
  575. MEM_INFO="\$(cat /proc/meminfo | awk '/MemTotal:/{total=\$2/1024/1024;next} /MemAvailable:/{use=total-\$2/1024/1024; printf("\033[0;33m%.2fGiB\033[0m of \033[1;34m%.2fGiB\033[0m RAM used (\033[0;33m%.2f%%\033[0m)",use,total,(use/total)*100);}')"
  576. # network
  577. # extranet_ip=" and \$(curl -s ip.cip.cc)"
  578. IP_INFO="\$(ip a|grep -E '^[0-9]+: em*|^[0-9]+: eno*|^[0-9]+: enp*|^[0-9]+: ens*|^[0-9]+: eth*|^[0-9]+: wlp*' -A2|grep inet|awk -F ' ' '{print $2}'|cut -f1 -d/|xargs echo)"
  579. # Container info
  580. CONTAINER_INFO="\$(sudo /usr/bin/crictl ps -a -o yaml 2> /dev/null | awk '/^ state: /{gsub("CONTAINER_", "", \$NF) ++S[\$NF]}END{for(m in S) printf "%s%s:%s ",substr(m,1,1),tolower(substr(m,2)),S[m]}')Images:\$(sudo /usr/bin/crictl images -q 2> /dev/null | wc -l)"
  581. # info
  582. echo -e "
  583. Information as of: \033[1;34m\$(date +"%Y-%m-%d %T")\033[0m
  584. \033[0;1;31mProduct\033[0m............: \${MODEL_INFO}
  585. \033[0;1;31mOS\033[0m.................: \${PRETTY_NAME}
  586. \033[0;1;31mKernel\033[0m.............: \${KERNEL}
  587. \033[0;1;31mCPU\033[0m................: \${CPU_INFO}
  588. \033[0;1;31mHostname\033[0m...........: \033[1;34m\$(hostname)\033[0m
  589. \033[0;1;31mIP Addresses\033[0m.......: \033[1;34m\${IP_INFO}\033[0m
  590. \033[0;1;31mUptime\033[0m.............: \033[0;33m\${UPTIME_INFO}\033[0m
  591. \033[0;1;31mMemory\033[0m.............: \${MEM_INFO}
  592. \033[0;1;31mLoad Averages\033[0m......: \${LOADAVG_INFO}
  593. \033[0;1;31mDisk Usage\033[0m.........: \${DISK_INFO}
  594. \033[0;1;31mUsers online\033[0m.......: \033[1;34m\${USER_NUM}\033[0m
  595. \033[0;1;31mRunning Processes\033[0m..: \033[1;34m\${RUNNING}\033[0m
  596. \033[0;1;31mContainer Info\033[0m.....: \${CONTAINER_INFO}
  597. "
  598. EOF
  599. chmod +x /etc/profile.d/zz-ssh-login-info.sh
  600. echo 'ALL ALL=(ALL) NOPASSWD:/usr/bin/crictl' > /etc/sudoers.d/crictl
  601. # time sync
  602. ntpd --help >/dev/null 2>&1 && yum remove -y ntp
  603. [[ "${OFFLINE_TAG:-}" != "1" ]] && yum install -y chrony
  604. [ ! -f /etc/chrony.conf_bak ] && cp /etc/chrony.conf{,_bak} #备份默认配置
  605. cat << EOF > /etc/chrony.conf
  606. server ntp.aliyun.com iburst
  607. server cn.ntp.org.cn iburst
  608. server ntp.shu.edu.cn iburst
  609. server 0.cn.pool.ntp.org iburst
  610. server 1.cn.pool.ntp.org iburst
  611. server 2.cn.pool.ntp.org iburst
  612. server 3.cn.pool.ntp.org iburst
  613. driftfile /var/lib/chrony/drift
  614. makestep 1.0 3
  615. logdir /var/log/chrony
  616. EOF
  617. timedatectl set-timezone Asia/Shanghai
  618. chronyd -q -t 1 'server cn.pool.ntp.org iburst maxsamples 1'
  619. systemctl enable chronyd
  620. systemctl start chronyd
  621. chronyc sources -v
  622. chronyc sourcestats
  623. hwclock --systohc
  624. # package
  625. [[ "${OFFLINE_TAG:-}" != "1" ]] && yum install -y curl wget
  626. # ipvs
  627. [[ "${OFFLINE_TAG:-}" != "1" ]] && yum install -y ipvsadm ipset sysstat conntrack libseccomp
  628. module=(
  629. ip_vs
  630. ip_vs_rr
  631. ip_vs_wrr
  632. ip_vs_sh
  633. overlay
  634. nf_conntrack
  635. br_netfilter
  636. )
  637. [ -f /etc/modules-load.d/ipvs.conf ] && cp -f /etc/modules-load.d/ipvs.conf{,_bak}
  638. for kernel_module in "${module[@]}";do
  639. /sbin/modinfo -F filename "$kernel_module" |& grep -qv ERROR && echo "$kernel_module" >> /etc/modules-load.d/ipvs.conf
  640. done
  641. systemctl restart systemd-modules-load
  642. systemctl enable systemd-modules-load
  643. sysctl --system
  644. # audit
  645. [[ "${OFFLINE_TAG:-}" != "1" ]] && yum install -y audit audit-libs
  646. # /etc/audit/rules.d/audit.rules
  647. cat << EOF >> /etc/audit/rules.d/audit.rules
  648. ## Kainstall managed start
  649. # Ignore errors
  650. -i
  651. # SYSCALL
  652. -a always,exit -F arch=b64 -S kill,tkill,tgkill -F a1=9 -F key=trace_kill_9
  653. -a always,exit -F arch=b64 -S kill,tkill,tgkill -F a1=15 -F key=trace_kill_15
  654. # docker
  655. -w /usr/bin/dockerd -k docker
  656. -w /var/lib/docker -k docker
  657. -w /etc/docker -k docker
  658. -w /usr/lib/systemd/system/docker.service -k docker
  659. -w /etc/systemd/system/docker.service -k docker
  660. -w /usr/lib/systemd/system/docker.socket -k docker
  661. -w /etc/default/docker -k docker
  662. -w /etc/sysconfig/docker -k docker
  663. -w /etc/docker/daemon.json -k docker
  664. # containerd
  665. -w /usr/bin/containerd -k containerd
  666. -w /var/lib/containerd -k containerd
  667. -w /usr/lib/systemd/system/containerd.service -k containerd
  668. -w /etc/containerd/config.toml -k containerd
  669. # cri-o
  670. -w /usr/bin/crio -k cri-o
  671. -w /etc/crio -k cri-o
  672. # runc
  673. -w /usr/bin/runc -k runc
  674. # kube
  675. -w /usr/bin/kubeadm -k kubeadm
  676. -w /usr/bin/kubelet -k kubelet
  677. -w /usr/bin/kubectl -k kubectl
  678. -w /var/lib/kubelet -k kubelet
  679. -w /etc/kubernetes -k kubernetes
  680. ## Kainstall managed end
  681. EOF
  682. chmod 600 /etc/audit/rules.d/audit.rules
  683. sed -i 's#max_log_file =.*#max_log_file = 80#g' /etc/audit/auditd.conf
  684. if [ -f /usr/libexec/initscripts/legacy-actions/auditd/restart ]; then
  685. /usr/libexec/initscripts/legacy-actions/auditd/restart
  686. else
  687. systemctl stop auditd && systemctl start auditd
  688. fi
  689. systemctl enable auditd
  690. grep single-request-reopen /etc/resolv.conf || sed -i '1ioptions timeout:2 attempts:3 rotate single-request-reopen' /etc/resolv.conf
  691. ipvsadm --clear
  692. iptables -F && iptables -t nat -F && iptables -t mangle -F && iptables -X
  693. }
  694. # 升级内核
  695. function script::upgrade_kernel() {
  696. local ver; ver=$(rpm --eval "%{centos_ver}")
  697. [[ "${OFFLINE_TAG:-}" != "1" ]] && yum install -y "https://www.elrepo.org/elrepo-release-${ver}.el${ver}.elrepo.noarch.rpm"
  698. sed -e "s/^mirrorlist=/#mirrorlist=/g" \
  699. -e "s/elrepo.org\/linux/mirrors.tuna.tsinghua.edu.cn\/elrepo/g" \
  700. -i /etc/yum.repos.d/elrepo.repo
  701. [[ "${OFFLINE_TAG:-}" != "1" ]] && yum install -y --disablerepo="*" --enablerepo=elrepo-kernel kernel-lt{,-devel}
  702. grub2-set-default 0 && grub2-mkconfig -o /etc/grub2.cfg
  703. grubby --default-kernel
  704. grubby --args="user_namespace.enable=1" --update-kernel="$(grubby --default-kernel)"
  705. }
  706. # 节点软件升级
  707. function script::upgrage_kube() {
  708. local role=${1:-init}
  709. local version="-${2:-latest}"
  710. version="${version#-latest}"
  711. set -e
  712. echo '[install] kubeadm'
  713. kubeadm version
  714. yum install -y "kubeadm${version}" --disableexcludes=kubernetes
  715. kubeadm version
  716. echo '[upgrade]'
  717. if [[ "$role" == "init" ]]; then
  718. local plan_info; plan_info=$(kubeadm upgrade plan)
  719. local v; v=$(printf "%s" "$plan_info" | grep 'kubeadm upgrade apply ' | awk '{print $4}'| tail -1 )
  720. printf "%s\n" "${plan_info}"
  721. kubeadm upgrade apply "${v}" -y
  722. else
  723. kubeadm upgrade node
  724. fi
  725. echo '[install] kubelet kubectl'
  726. kubectl version --client=true
  727. yum install -y "kubelet${version}" "kubectl${version}" --disableexcludes=kubernetes
  728. kubectl version --client=true
  729. [ -f /usr/lib/systemd/system/kubelet.service.d/10-kubeadm.conf ] && \
  730. sed -i 's#^\[Service\]#[Service]\nCPUAccounting=true\nMemoryAccounting=true#g' /usr/lib/systemd/system/kubelet.service.d/10-kubeadm.conf
  731. systemctl daemon-reload
  732. systemctl restart kubelet
  733. }
  734. # 安装 docker
  735. function script::install_docker() {
  736. #local version="-${1:-latest}"
  737. #version="${version#-latest}"
  738. cat << EOF > /etc/yum.repos.d/docker-ce.repo
  739. [docker-ce-stable]
  740. name=Docker CE Stable - \$basearch
  741. baseurl=https://mirrors.aliyun.com/docker-ce/linux/centos/$(rpm --eval '%{centos_ver}')/\$basearch/stable
  742. enabled=1
  743. gpgcheck=1
  744. gpgkey=https://mirrors.aliyun.com/docker-ce/linux/centos/gpg
  745. EOF
  746. if [[ "${OFFLINE_TAG:-}" != "1" ]];then
  747. [ -f "$(which docker)" ] && yum remove -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin docker-ce-rootless-extras
  748. yum install -y "docker-ce-20.10.24-3.el7" "docker-ce-cli-20.10.24-3.el7" containerd.io bash-completion
  749. fi
  750. [ -f /usr/share/bash-completion/completions/docker ] && \
  751. cp -f /usr/share/bash-completion/completions/docker /etc/bash_completion.d/
  752. [ ! -d /etc/docker ] && mkdir /etc/docker
  753. # /etc/docker/daemon.json
  754. cat << EOF > /etc/docker/daemon.json
  755. {
  756. "data-root": "/var/lib/docker",
  757. "log-driver": "json-file",
  758. "log-opts": {
  759. "max-size": "200m",
  760. "max-file": "3"
  761. },
  762. "default-ulimits": {
  763. "nofile": {
  764. "Name": "nofile",
  765. "Hard": 655360,
  766. "Soft": 655360
  767. },
  768. "nproc": {
  769. "Name": "nproc",
  770. "Hard": 655360,
  771. "Soft": 655360
  772. }
  773. },
  774. "live-restore": true,
  775. "max-concurrent-downloads": 10,
  776. "max-concurrent-uploads": 10,
  777. "registry-mirrors": [
  778. ],
  779. "insecure-registries": [
  780. ]
  781. }
  782. EOF
  783. sed -i 's|#oom_score = 0|oom_score = -999|' /etc/containerd/config.toml
  784. # /etc/crictl.yaml
  785. cat << EOF > /etc/crictl.yaml
  786. runtime-endpoint: unix:///var/run/dockershim.sock
  787. image-endpoint: unix:///var/run/dockershim.sock
  788. timeout: 2
  789. debug: false
  790. pull-image-on-create: true
  791. disable-pull-on-run: false
  792. EOF
  793. systemctl enable containerd
  794. systemctl restart containerd
  795. systemctl enable docker
  796. systemctl restart docker
  797. }
  798. # 安装 containerd
  799. function script::install_containerd() {
  800. local version="-${1:-latest}"
  801. version="${version#-latest}"
  802. # /etc/yum.repos.d/docker-ce.repo
  803. cat << EOF > /etc/yum.repos.d/docker-ce.repo
  804. [docker-ce-stable]
  805. name=Docker CE Stable - \$basearch
  806. baseurl=https://mirrors.aliyun.com/docker-ce/linux/centos/$(rpm --eval '%{centos_ver}')/\$basearch/stable
  807. enabled=1
  808. gpgcheck=1
  809. gpgkey=https://mirrors.aliyun.com/docker-ce/linux/centos/gpg
  810. EOF
  811. if [[ "${OFFLINE_TAG:-}" != "1" ]];then
  812. [ -f "$(which runc)" ] && yum remove -y runc
  813. [ -f "$(which containerd)" ] && yum remove -y containerd.io
  814. yum install -y containerd.io"${version}" containernetworking bash-completion
  815. fi
  816. [ -d /etc/bash_completion.d ] && crictl completion bash > /etc/bash_completion.d/crictl
  817. containerd config default > /etc/containerd/config.toml
  818. sed -i -e "s#k8s.gcr.io#registry.cn-hangzhou.aliyuncs.com/kainstall#g" \
  819. -e "s#SystemdCgroup = false#SystemdCgroup = true#g" \
  820. -e "s#oom_score = 0#oom_score = -999#" \
  821. -e "s#max_concurrent_downloads = 3#max_concurrent_downloads = 10#g" /etc/containerd/config.toml
  822. # /etc/crictl.yaml
  823. cat << EOF > /etc/crictl.yaml
  824. runtime-endpoint: unix:///run/containerd/containerd.sock
  825. image-endpoint: unix:///run/containerd/containerd.sock
  826. timeout: 2
  827. debug: false
  828. pull-image-on-create: true
  829. disable-pull-on-run: false
  830. EOF
  831. systemctl restart containerd
  832. systemctl enable containerd
  833. }
  834. # 安装 cri-o
  835. function script::install_cri-o() {
  836. local version="${1:-latest}"
  837. version="${version#-latest}"
  838. os="CentOS_$(rpm --eval '%{centos_ver}')" && echo "${os}"
  839. # /etc/yum.repos.d/devel_kubic_libcontainers_stable.repo
  840. cat << EOF > /etc/yum.repos.d/devel_kubic_libcontainers_stable.repo
  841. [devel_kubic_libcontainers_stable]
  842. name=Stable Releases of Upstream github.com/containers packages
  843. type=rpm-md
  844. baseurl=https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/${os}/
  845. gpgcheck=1
  846. gpgkey=https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/${os}/repodata/repomd.xml.key
  847. enabled=1
  848. [devel_kubic_libcontainers_stable_cri-o]
  849. name=devel:kubic:libcontainers:stable:cri-o
  850. type=rpm-md
  851. baseurl=https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable:/cri-o:/${version}/${os}/
  852. gpgcheck=1
  853. gpgkey=https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable:/cri-o:/${version}/${os}/repodata/repomd.xml.key
  854. enabled=1
  855. EOF
  856. if [[ "${OFFLINE_TAG:-}" != "1" ]];then
  857. [ -f "$(which runc)" ] && yum remove -y runc
  858. [ -f "$(which crio)" ] && yum remove -y cri-o
  859. [ -f "$(which docker)" ] && yum remove -y docker-ce docker-ce-cli containerd.io
  860. yum install -y runc cri-o bash-completion --disablerepo=docker-ce-stable || yum install -y runc cri-o bash-completion
  861. fi
  862. [ -d /etc/bash_completion.d ] && \
  863. { crictl completion bash > /etc/bash_completion.d/crictl; \
  864. crio completion bash > /etc/bash_completion.d/crio; \
  865. crio-status completion bash > /etc/bash_completion.d/crio-status; }
  866. [ ! -f /etc/crio/crio.conf ] && crio config --default > /etc/crio/crio.conf
  867. sed -i -e "s#k8s.gcr.io#registry.cn-hangzhou.aliyuncs.com/kainstall#g" \
  868. -e 's|#registries = \[|registries = ["docker.io", "quay.io"]|g' /etc/crio/crio.conf
  869. # /etc/crio/crio.conf
  870. cat << EOF >> /etc/crio/crio.conf
  871. [crio.image]
  872. pause_image = "registry.cn-hangzhou.aliyuncs.com/kainstall/pause:3.6"
  873. EOF
  874. # /etc/containers/registries.conf.d/000-dockerio.conf
  875. [ -d /etc/containers/registries.conf.d ] && cat << EOF > /etc/containers/registries.conf.d/000-dockerio.conf
  876. [[registry]]
  877. prefix = "docker.io"
  878. insecure = false
  879. blocked = false
  880. location = "docker.io"
  881. EOF
  882. # /etc/crictl.yaml
  883. cat << EOF > /etc/crictl.yaml
  884. runtime-endpoint: unix:///var/run/crio/crio.sock
  885. image-endpoint: unix:///var/run/crio/crio.sock
  886. timeout: 2
  887. debug: false
  888. pull-image-on-create: true
  889. disable-pull-on-run: false
  890. EOF
  891. # /etc/cni/net.d/100-crio-bridge.conf
  892. sed -i "s#10.85.0.0/16#${KUBE_POD_SUBNET:-10.85.0.0/16}#g" /etc/cni/net.d/100-crio-bridge.conf
  893. # /etc/cni/net.d/10-crio.conf
  894. cat << EOF > /etc/cni/net.d/10-crio.conf
  895. {
  896. $(grep cniVersion /etc/cni/net.d/100-crio-bridge.conf)
  897. "name": "crio",
  898. "type": "flannel"
  899. }
  900. EOF
  901. mv /etc/cni/net.d/100-crio-bridge.conf /etc/cni/net.d/10-crio.conf /etc/cni/net.d/200-loopback.conf /tmp/
  902. systemctl restart crio
  903. systemctl enable crio
  904. }
  905. # 安装kube组件
  906. function script::install_kube() {
  907. local version="-${1:-latest}"
  908. version="${version#-latest}"
  909. # /etc/yum.repos.d/kubernetes.repo
  910. cat <<EOF > /etc/yum.repos.d/kubernetes.repo
  911. [kubernetes]
  912. name=Kubernetes
  913. baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
  914. enabled=1
  915. gpgcheck=0
  916. repo_gpgcheck=0
  917. gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
  918. EOF
  919. if [[ "${OFFLINE_TAG:-}" != "1" ]];then
  920. [ -f /usr/bin/kubeadm ] && yum remove -y kubeadm
  921. [ -f /usr/bin/kubelet ] && yum remove -y kubelet
  922. [ -f /usr/bin/kubectl ] && yum remove -y kubectl
  923. yum install -y "kubeadm${version}" "kubelet${version}" "kubectl${version}" --disableexcludes=kubernetes
  924. fi
  925. [ -d /etc/bash_completion.d ] && \
  926. { kubectl completion bash > /etc/bash_completion.d/kubectl; \
  927. kubeadm completion bash > /etc/bash_completion.d/kubadm; }
  928. [ ! -d /usr/lib/systemd/system/kubelet.service.d ] && mkdir -p /usr/lib/systemd/system/kubelet.service.d
  929. cat << EOF > /usr/lib/systemd/system/kubelet.service.d/11-cgroup.conf
  930. [Service]
  931. CPUAccounting=true
  932. MemoryAccounting=true
  933. BlockIOAccounting=true
  934. ExecStartPre=/bin/bash -c '/bin/mkdir -p /sys/fs/cgroup/{cpuset,memory,hugetlb,systemd,pids,"cpu,cpuacct"}/{system,kube,kubepods}.slice||:'
  935. Slice=kube.slice
  936. EOF
  937. systemctl daemon-reload
  938. systemctl enable kubelet
  939. systemctl restart kubelet
  940. }
  941. # 安装haproxy
  942. function script::install_haproxy() {
  943. local api_servers="$*"
  944. if [[ "${OFFLINE_TAG:-}" != "1" ]];then
  945. [ -f /usr/bin/haproxy ] && yum remove -y haproxy
  946. yum install -y haproxy
  947. fi
  948. # /etc/haproxy/haproxy.cfg
  949. [ ! -f /etc/haproxy/haproxy.cfg_bak ] && cp /etc/haproxy/haproxy.cfg{,_bak}
  950. cat << EOF > /etc/haproxy/haproxy.cfg
  951. global
  952. log /dev/log local0
  953. log /dev/log local1 notice
  954. tune.ssl.default-dh-param 2048
  955. defaults
  956. log global
  957. mode http
  958. option dontlognull
  959. timeout connect 5000ms
  960. timeout client 600000ms
  961. timeout server 600000ms
  962. listen stats
  963. bind :19090
  964. mode http
  965. balance
  966. stats uri /haproxy_stats
  967. stats auth admin:admin123
  968. stats admin if TRUE
  969. frontend kube-apiserver-https
  970. mode tcp
  971. option tcplog
  972. bind :6443
  973. default_backend kube-apiserver-backend
  974. backend kube-apiserver-backend
  975. mode tcp
  976. balance roundrobin
  977. stick-table type ip size 200k expire 30m
  978. stick on src
  979. $(index=1;for h in $api_servers;do echo " server apiserver${index} $h:6443 check";index=$((index+1));done)
  980. EOF
  981. systemctl enable haproxy
  982. systemctl restart haproxy
  983. }
  984. # 安装helm
  985. function script::install_helm() {
  986. local version="${1:-3.10.1}"
  987. version="${version#-3.10.1}"
  988. local path="/tmp"
  989. cd $path
  990. # 下载软件(国内源)
  991. wget https://mirrors.huaweicloud.com/helm/v$version/helm-v$version-linux-amd64.tar.gz
  992. # 解压
  993. tar -zxvf helm-v$version-linux-amd64.tar.gz
  994. # 安装
  995. sudo mv linux-amd64/helm /usr/local/bin/
  996. # 清理
  997. rm -rf helm-v$version-linux-amd64.tar.gz linux-amd64
  998. # 验证
  999. helm version
  1000. cd ~
  1001. }
  1002. # 检查用到的命令
  1003. function check::command() {
  1004. check::command_exists ssh openssh-clients
  1005. check::command_exists sshpass sshpass
  1006. check::command_exists wget wget
  1007. [[ "${OFFLINE_TAG:-}" == "1" ]] && check::command_exists tar tar
  1008. }
  1009. # 检查ssh连通性
  1010. function check::ssh_conn() {
  1011. for host in $MASTER_NODES $WORKER_NODES
  1012. do
  1013. [ "$host" == "127.0.0.1" ] && continue
  1014. command::exec "${host}" "echo 0"
  1015. check::exit_code "$?" "check" "ssh $host connection" "exit"
  1016. done
  1017. }
  1018. # 检查os系统支持
  1019. function check::os() {
  1020. log::info "[check]" "os support: ${OS_SUPPORT}"
  1021. for host in $MASTER_NODES $WORKER_NODES
  1022. do
  1023. command::exec "${host}" "
  1024. [ -f /etc/os-release ] && source /etc/os-release
  1025. echo client_os:\${ID:-}\${VERSION_ID:-}
  1026. if [[ \"${OS_SUPPORT}\" == *\"\${ID:-}\${VERSION_ID:-}\"* ]]; then
  1027. exit 0
  1028. fi
  1029. exit 1
  1030. "
  1031. check::exit_code "$?" "check" "$host os support" "exit"
  1032. done
  1033. }
  1034. # 检查os kernel 版本
  1035. function check::kernel() {
  1036. local version=${1:-}
  1037. log::info "[check]" "kernel version not less than ${version}"
  1038. version=$(echo "${version}" | awk -F. '{ printf("%d%03d%03d\n", $1,$2,$3); }')
  1039. for host in $MASTER_NODES $WORKER_NODES
  1040. do
  1041. command::exec "${host}" "
  1042. kernel_version=\$(uname -r)
  1043. kernel_version=\$(echo \${kernel_version/-*} | awk -F. '{ printf(\"%d%03d%03d\n\", \$1,\$2,\$3); }')
  1044. echo kernel_version \${kernel_version}
  1045. [[ \${kernel_version} -ge ${version} ]] && exit 0 || exit 1
  1046. "
  1047. check::exit_code "$?" "check" "$host kernel version" "exit"
  1048. done
  1049. }
  1050. # 检查api-server连通性
  1051. function check::apiserver_conn() {
  1052. command::exec "${MGMT_NODE}" "kubectl get node"
  1053. check::exit_code "$?" "check" "conn apiserver" "exit"
  1054. }
  1055. # 检查返回码
  1056. function check::exit_code() {
  1057. local code=${1:-}
  1058. local app=${2:-}
  1059. local desc=${3:-}
  1060. local exit_script=${4:-}
  1061. if [[ "${code}" == "0" ]]; then
  1062. log::info "[${app}]" "${desc} succeeded."
  1063. else
  1064. log::error "[${app}]" "${desc} failed."
  1065. [[ "$exit_script" == "exit" ]] && exit "$code"
  1066. fi
  1067. }
  1068. # 预检
  1069. function check::preflight() {
  1070. # check command
  1071. check::command
  1072. # check ssh conn
  1073. check::ssh_conn
  1074. # check os
  1075. check::os
  1076. # check os kernel
  1077. [[ "${KUBE_NETWORK:-}" == "cilium" ]] && check::kernel 4.9.17
  1078. # check api-server conn
  1079. if [[ $(( ${ADD_TAG:-0} + ${DEL_TAG:-0} + ${UPGRADE_TAG:-0} + ${RENEW_CERT_TAG:-0} )) -gt 0 ]]; then
  1080. check::apiserver_conn
  1081. fi
  1082. }
  1083. # 安装包
  1084. function install::package() {
  1085. # 检查k8s最新稳定版本
  1086. if [[ "${KUBE_CRI}" == "cri-o" && "${KUBE_CRI_VERSION}" == "latest" ]]; then
  1087. KUBE_CRI_VERSION="${KUBE_VERSION}"
  1088. if [[ "${KUBE_CRI_VERSION}" == "latest" ]]; then
  1089. if command::exec "127.0.0.1" "wget https://storage.googleapis.com/kubernetes-release/release/stable.txt -q -O -"; then
  1090. KUBE_CRI_VERSION="${COMMAND_OUTPUT#v}"
  1091. else
  1092. log::error "[install]" "get kubernetes stable version error. Please specify the version!"
  1093. exit 1
  1094. fi
  1095. fi
  1096. KUBE_CRI_VERSION="${KUBE_CRI_VERSION%.*}"
  1097. fi
  1098. # 安装 cri kube
  1099. for host in $MASTER_NODES $WORKER_NODES
  1100. do
  1101. # install cri
  1102. log::info "[install]" "install ${KUBE_CRI} on $host."
  1103. command::exec "${host}" "
  1104. export OFFLINE_TAG=${OFFLINE_TAG:-0}
  1105. $(declare -f script::install_"${KUBE_CRI}")
  1106. script::install_${KUBE_CRI} $KUBE_CRI_VERSION
  1107. "
  1108. check::exit_code "$?" "install" "install ${KUBE_CRI} on $host"
  1109. # install kube
  1110. log::info "[install]" "install kube on $host"
  1111. command::exec "${host}" "
  1112. export OFFLINE_TAG=${OFFLINE_TAG:-0}
  1113. $(declare -f script::install_kube)
  1114. script::install_kube $KUBE_VERSION
  1115. "
  1116. check::exit_code "$?" "install" "install kube on $host"
  1117. done
  1118. # 配置 kube
  1119. local apiservers=$MASTER_NODES
  1120. if [[ "$apiservers" == "127.0.0.1" ]]; then
  1121. command::exec "${MGMT_NODE}" "ip -o route get to 8.8.8.8 | sed -n 's/.*src \([0-9.]\+\).*/\1/p'"
  1122. get::command_output "apiservers" "$?"
  1123. fi
  1124. # 输出 api-servers 信息
  1125. if [[ "${ADD_TAG:-}" == "1" ]]; then
  1126. command::exec "${MGMT_NODE}" "
  1127. kubectl get node --selector='node-role.kubernetes.io/master' -o jsonpath='{$.items[*].status.addresses[?(@.type==\"InternalIP\")].address}'
  1128. "
  1129. get::command_output "apiservers" "$?"
  1130. fi
  1131. # 安装 haproxy
  1132. for host in $WORKER_NODES
  1133. do
  1134. # install haproxy
  1135. log::info "[install]" "install haproxy on $host"
  1136. command::exec "${host}" "
  1137. export OFFLINE_TAG=${OFFLINE_TAG:-0}
  1138. $(declare -f script::install_haproxy)
  1139. script::install_haproxy \"$apiservers\"
  1140. "
  1141. check::exit_code "$?" "install" "install haproxy on $host"
  1142. done
  1143. # 10年证书
  1144. if [[ "${CERT_YEAR_TAG:-}" == "1" ]]; then
  1145. local version="${KUBE_VERSION}"
  1146. if [[ "${version}" == "latest" ]]; then
  1147. if command::exec "127.0.0.1" "wget https://storage.googleapis.com/kubernetes-release/release/stable.txt -q -O -"; then
  1148. version="${COMMAND_OUTPUT#v}"
  1149. else
  1150. log::error "[install]" "get kubernetes stable version error. Please specify the version!"
  1151. exit 1
  1152. fi
  1153. fi
  1154. log::info "[install]" "download kubeadm 10 years certs client"
  1155. local certs_file="${OFFLINE_DIR}/bins/kubeadm-linux-amd64"
  1156. MGMT_NODE="127.0.0.1" utils::download_file "${GITHUB_PROXY}https://github.com/lework/kubeadm-certs/releases/download/v${version}/kubeadm-linux-amd64" "${certs_file}"
  1157. for host in $MASTER_NODES $WORKER_NODES
  1158. do
  1159. log::info "[install]" "scp kubeadm client to $host"
  1160. command::scp "${host}" "${certs_file}" "/tmp/kubeadm-linux-amd64"
  1161. check::exit_code "$?" "install" "scp kubeadm client to $host" "exit"
  1162. command::exec "${host}" "
  1163. set -e
  1164. if [[ -f /tmp/kubeadm-linux-amd64 ]]; then
  1165. [[ -f /usr/bin/kubeadm && ! -f /usr/bin/kubeadm_src ]] && mv -fv /usr/bin/kubeadm{,_src}
  1166. mv -fv /tmp/kubeadm-linux-amd64 /usr/bin/kubeadm
  1167. chmod +x /usr/bin/kubeadm
  1168. else
  1169. echo \"not found /tmp/kubeadm-linux-amd64\"
  1170. exit 1
  1171. fi
  1172. "
  1173. check::exit_code "$?" "install" "$host: use kubeadm 10 years certs client"
  1174. done
  1175. fi
  1176. # 安装helm
  1177. for host in $MASTER_NODES $WORKER_NODES
  1178. do
  1179. log::info "[install]" "install helm on $host"
  1180. command::exec "${host}" "
  1181. export OFFLINE_TAG=${OFFLINE_TAG:-0}
  1182. $(declare -f script::install_helm)
  1183. script::install_helm $HELM_VERSION
  1184. "
  1185. check::exit_code "$?" "install" "install helm on $host"
  1186. done
  1187. }
  1188. # 升级节点内核
  1189. function init::upgrade_kernel() {
  1190. [[ "${UPGRADE_KERNEL_TAG:-}" != "1" ]] && return
  1191. for host in $MASTER_NODES $WORKER_NODES
  1192. do
  1193. log::info "[init]" "upgrade kernel: $host"
  1194. command::exec "${host}" "
  1195. export OFFLINE_TAG=${OFFLINE_TAG:-0}
  1196. $(declare -f script::upgrade_kernel)
  1197. script::upgrade_kernel
  1198. "
  1199. check::exit_code "$?" "init" "upgrade kernel $host" "exit"
  1200. done
  1201. for host in $MASTER_NODES $WORKER_NODES
  1202. do
  1203. command::exec "${host}" "bash -c 'sleep 15 && reboot' &>/dev/null &"
  1204. check::exit_code "$?" "init" "$host: Wait for 15s to restart"
  1205. done
  1206. log::info "[notice]" "Please execute the command again!"
  1207. log::access "[command]" "bash $0 ${SCRIPT_PARAMETER// --upgrade-kernel/}"
  1208. exit 0
  1209. }
  1210. # 节点证书续期
  1211. function cert::renew_node() {
  1212. local role="${1:-master}"
  1213. local hosts=""
  1214. local kubelet_config=""
  1215. command::exec "${MGMT_NODE}" "
  1216. kubectl get node --selector='node-role.kubernetes.io/${role}' -o jsonpath='{range.items[*]}{.metadata.name } {end}'
  1217. "
  1218. get::command_output "hosts" "$?"
  1219. for host in ${hosts}
  1220. do
  1221. log::info "[cert]" "drain $host"
  1222. command::exec "${MGMT_NODE}" "kubectl drain $host --force --ignore-daemonsets --delete-local-data"
  1223. check::exit_code "$?" "cert" "$host: drain"
  1224. sleep 5
  1225. if [[ "${role}" == "master" ]]; then
  1226. command::exec "${host}" "cp -rf /etc/kubernetes /etc/kubernetes_\$(date +%Y-%m-%d)"
  1227. check::exit_code "$?" "cert" "$host: backup kubernetes config"
  1228. command::exec "${host}" "kubeadm certs renew all 2>/dev/null|| kubeadm alpha certs renew all"
  1229. check::exit_code "$?" "cert" "$host: renew certs"
  1230. command::exec "${host}" "
  1231. $(declare -f utils::retry)
  1232. kill -s SIGHUP \$(pidof etcd) && \
  1233. utils::retry 10 \"echo -n | openssl s_client -connect localhost:2379 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | openssl x509 -text -noout | grep Not\"
  1234. "
  1235. check::exit_code "$?" "cert" "$host: restart etcd"
  1236. command::exec "${host}" "
  1237. $(declare -f utils::retry)
  1238. kill -s SIGHUP \$(pidof kube-apiserver) && \
  1239. utils::retry 10 \"echo -n | openssl s_client -connect localhost:6443 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | openssl x509 -text -noout | grep Not\"
  1240. "
  1241. check::exit_code "$?" "cert" "$host: restart kube-apiserver"
  1242. command::exec "${host}" "
  1243. $(declare -f utils::retry)
  1244. kill -s SIGHUP \$(pidof kube-controller-manager) && \
  1245. utils::retry 10 \"echo -n | openssl s_client -connect localhost:10257 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | openssl x509 -text -noout | grep Not\"
  1246. "
  1247. check::exit_code "$?" "cert" "$host: restart kube-controller-manager"
  1248. command::exec "${host}" "
  1249. $(declare -f utils::retry)
  1250. kill -s SIGHUP \$(pidof kube-scheduler) && \
  1251. utils::retry 10 \"echo -n | openssl s_client -connect localhost:10259 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | openssl x509 -text -noout | grep Not\"
  1252. "
  1253. check::exit_code "$?" "cert" "$host: restart kube-scheduler"
  1254. fi
  1255. log::info "[cert]" "get kubelet config"
  1256. command::exec "${MGMT_NODE}" "
  1257. kubeadm kubeconfig user --org system:nodes --client-name system:node:${host} --config /etc/kubernetes/kubeadmcfg.yaml || kubeadm alpha kubeconfig user --org system:nodes --client-name system:node:${host} --config /etc/kubernetes/kubeadmcfg.yaml
  1258. "
  1259. get::command_output "kubelet_config" "$?" "exit"
  1260. if [[ "$kubelet_config" != "" ]]; then
  1261. log::info "[cert]" "copy kubelet config"
  1262. command::exec "${host}" "
  1263. cp /etc/kubernetes/kubelet.conf /etc/kubernetes/kubelet.conf_bak
  1264. echo '$(printf "%s" "${kubelet_config}" | sed 's#https://.*:#https://127.0.0.1:#g')' > /etc/kubernetes/kubelet.conf
  1265. "
  1266. check::exit_code "$?" "cert" "$host: copy kubelet config"
  1267. command::exec "${host}" "rm -rfv /var/lib/kubelet/pki/*"
  1268. check::exit_code "$?" "cert" "$host: delete kubelet pki files"
  1269. command::exec "${host}" "
  1270. $(declare -f utils::retry)
  1271. systemctl restart kubelet && \
  1272. utils::retry 10 \"echo -n | openssl s_client -connect localhost:10250 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | openssl x509 -text -noout | grep Not\"
  1273. "
  1274. local status="$?"
  1275. check::exit_code "${status}" "cert" "$host: restart kubelet"
  1276. if [[ "${status}" == "0" ]]; then
  1277. sleep 5
  1278. command::exec "${MGMT_NODE}" "kubectl uncordon ${host}"
  1279. check::exit_code "$?" "cert" "uncordon ${host} node"
  1280. fi
  1281. fi
  1282. done
  1283. }
  1284. # 证书续期
  1285. function cert::renew() {
  1286. log::info "[cert]" "renew cluster cert"
  1287. cert::renew_node "master"
  1288. cert::renew_node "worker"
  1289. log::info "[cert]" "cluster status"
  1290. command::exec "${MGMT_NODE}" "
  1291. echo
  1292. kubectl get node
  1293. echo
  1294. kubeadm certs check-expiration 2>/dev/null || kubeadm alpha certs check-expiration
  1295. " && printf "%s" "${COMMAND_OUTPUT}"
  1296. }
  1297. # 初始化节点配置
  1298. function init::node_config() {
  1299. local master_index=${master_index:-1}
  1300. local worker_index=${worker_index:-1}
  1301. # 获取MGMT_NODE机器的内网IP
  1302. if [[ "$MGMT_NODE" == "127.0.0.1" || "$MGMT_NODE_IP" == "" ]]; then
  1303. log::info "[init]" "Get $MGMT_NODE InternalIP."
  1304. command::exec "${MGMT_NODE}" "
  1305. ip -4 route get 8.8.8.8 2>/dev/null | head -1 | awk '{print \$7}'
  1306. "
  1307. get::command_output "MGMT_NODE_IP" "$?" "exit"
  1308. if [[ "$MGMT_NODE" != "$MGMT_NODE_IP" ]]; then
  1309. log::warning "[init]" "ip不相同: $MGMT_NODE(MGMT_NODE) != $MGMT_NODE_IP(MGMT_NODE_IP)"
  1310. fi
  1311. else
  1312. MGMT_NODE_IP=$MGMT_NODE
  1313. fi
  1314. # master
  1315. for host in $MASTER_NODES
  1316. do
  1317. log::info "[init]" "master: $host"
  1318. command::exec "${host}" "
  1319. export OFFLINE_TAG=${OFFLINE_TAG:-0} KUBE_APISERVER=${KUBE_APISERVER} SKIP_SET_OS_REPO=${SKIP_SET_OS_REPO:-false}
  1320. $(declare -f script::init_node)
  1321. script::init_node
  1322. "
  1323. check::exit_code "$?" "init" "init master $host" "exit"
  1324. # 设置主机名和解析
  1325. command::exec "${host}" "
  1326. printf \"\\n${MGMT_NODE_IP} $KUBE_APISERVER\\n$node_hosts\" >> /etc/hosts
  1327. hostnamectl set-hostname ${HOSTNAME_PREFIX}-master-node${master_index}
  1328. "
  1329. check::exit_code "$?" "init" "$host set hostname and hostname resolution"
  1330. # set audit-policy
  1331. log::info "[init]" "$host: set audit-policy file."
  1332. command::exec "${host}" "
  1333. [ ! -d etc/kubernetes ] && mkdir -p /etc/kubernetes
  1334. cat << EOF > /etc/kubernetes/audit-policy.yaml
  1335. # Log all requests at the Metadata level.
  1336. apiVersion: audit.k8s.io/v1
  1337. kind: Policy
  1338. rules:
  1339. - level: Metadata
  1340. EOF
  1341. "
  1342. check::exit_code "$?" "init" "$host: set audit-policy file" "exit"
  1343. master_index=$((master_index + 1))
  1344. done
  1345. # worker
  1346. for host in $WORKER_NODES
  1347. do
  1348. log::info "[init]" "worker: $host"
  1349. command::exec "${host}" "
  1350. export OFFLINE_TAG=${OFFLINE_TAG:-0} KUBE_APISERVER=${KUBE_APISERVER} SKIP_SET_OS_REPO=${SKIP_SET_OS_REPO:-false}
  1351. $(declare -f script::init_node)
  1352. script::init_node
  1353. "
  1354. check::exit_code "$?" "init" "init worker $host" "exit"
  1355. # 设置主机名和解析
  1356. command::exec "${host}" "
  1357. printf \"\\n127.0.0.1 $KUBE_APISERVER\\n$node_hosts\" >> /etc/hosts
  1358. hostnamectl set-hostname ${HOSTNAME_PREFIX}-worker-node${worker_index}
  1359. "
  1360. worker_index=$((worker_index + 1))
  1361. done
  1362. }
  1363. # 初始化节点
  1364. function init::node() {
  1365. init::upgrade_kernel
  1366. local node_hosts=""
  1367. local i=1
  1368. for h in $MASTER_NODES
  1369. do
  1370. node_hosts="${node_hosts}\n$h ${HOSTNAME_PREFIX}-master-node${i}"
  1371. i=$((i + 1))
  1372. done
  1373. local i=1
  1374. for h in $WORKER_NODES
  1375. do
  1376. node_hosts="${node_hosts}\n$h ${HOSTNAME_PREFIX}-worker-node${i}"
  1377. i=$((i + 1))
  1378. done
  1379. init::node_config
  1380. }
  1381. # 初始化添加的节点
  1382. function init::add_node() {
  1383. init::upgrade_kernel
  1384. local master_index=0
  1385. local worker_index=0
  1386. local node_hosts=""
  1387. local add_node_hosts=""
  1388. command::exec "${MGMT_NODE}" "
  1389. kubectl get node --selector='node-role.kubernetes.io/master' -o jsonpath='{range.items[*]}{.status.addresses[?(@.type==\"InternalIP\")].address } {end}' | awk '{print \$1}'
  1390. "
  1391. get::command_output "MGMT_NODE" "$?" "exit"
  1392. # 获取现有集群节点主机名
  1393. command::exec "${MGMT_NODE}" "
  1394. kubectl get node -o jsonpath='{range.items[*]}{.status.addresses[?(@.type==\"InternalIP\")].address} {.metadata.name }\\n{end}'
  1395. "
  1396. get::command_output "node_hosts" "$?" "exit"
  1397. for host in $MASTER_NODES $WORKER_NODES
  1398. do
  1399. if [[ $node_hosts == *"$host"* ]]; then
  1400. log::error "[init]" "The host $host is already in the cluster!"
  1401. exit 1
  1402. fi
  1403. done
  1404. if [[ "$MASTER_NODES" != "" ]]; then
  1405. command::exec "${MGMT_NODE}" "
  1406. kubectl get node --selector='node-role.kubernetes.io/master' -o jsonpath='{\$.items[*].metadata.name}' |grep -Eo 'node[0-9]*'|grep -Eo '[0-9]*'|awk -F ' ' 'BEGIN {max = 0} {if (\$0+0 > max+0) max=\$0} END {print max}'
  1407. "
  1408. get::command_output "master_index" "$?" "exit"
  1409. master_index=$(( master_index + 1 ))
  1410. local i=$master_index
  1411. for host in $MASTER_NODES
  1412. do
  1413. add_node_hosts="${add_node_hosts}\n${host:-} ${HOSTNAME_PREFIX}-master-node${i}"
  1414. i=$((i + 1))
  1415. done
  1416. fi
  1417. if [[ "$WORKER_NODES" != "" ]]; then
  1418. command::exec "${MGMT_NODE}" "
  1419. kubectl get node --selector='node-role.kubernetes.io/worker' -o jsonpath='{\$.items[*].metadata.name}'| grep -Eo 'node[0-9]*'|grep -Eo '[0-9]*'|awk 'BEGIN {max = 0} {if (\$0+0 > max+0) max=\$0} END {print max}' || echo 0
  1420. "
  1421. get::command_output "worker_index" "$?" "exit"
  1422. worker_index=$(( worker_index + 1 ))
  1423. local i=$worker_index
  1424. for host in $WORKER_NODES
  1425. do
  1426. add_node_hosts="${add_node_hosts}\n${host:-} ${HOSTNAME_PREFIX}-worker-node${i}"
  1427. i=$((i + 1))
  1428. done
  1429. fi
  1430. # 向集群节点添加新增的节点主机名解析
  1431. for host in $(echo -ne "$node_hosts" | awk '{print $1}')
  1432. do
  1433. command::exec "${host}" "
  1434. printf \"$add_node_hosts\" >> /etc/hosts
  1435. "
  1436. check::exit_code "$?" "init" "$host add new node hostname resolution"
  1437. done
  1438. node_hosts="${node_hosts}\n${add_node_hosts}"
  1439. init::node_config
  1440. }
  1441. # 集群初始化
  1442. function kubeadm::init() {
  1443. log::info "[kubeadm init]" "kubeadm init on ${MGMT_NODE}"
  1444. log::info "[kubeadm init]" "${MGMT_NODE}: set kubeadmcfg.yaml"
  1445. command::exec "${MGMT_NODE}" "
  1446. PAUSE_VERSION=$(kubeadm config images list 2>/dev/null | awk -F: '/pause/ {print $2}')
  1447. cat << EOF > /etc/kubernetes/kubeadmcfg.yaml
  1448. ---
  1449. apiVersion: kubeadm.k8s.io/v1beta2
  1450. kind: InitConfiguration
  1451. ${kubelet_nodeRegistration}
  1452. ---
  1453. apiVersion: kubeproxy.config.k8s.io/v1alpha1
  1454. kind: KubeProxyConfiguration
  1455. mode: ipvs
  1456. ipvs:
  1457. minSyncPeriod: 5s
  1458. syncPeriod: 5s
  1459. # ipvs 负载策略
  1460. scheduler: 'wrr'
  1461. ---
  1462. apiVersion: kubelet.config.k8s.io/v1beta1
  1463. kind: KubeletConfiguration
  1464. maxPods: 200
  1465. cgroupDriver: systemd
  1466. runtimeRequestTimeout: 5m
  1467. # 此配置保证了 kubelet 能在 swap 开启的情况下启动
  1468. failSwapOn: false
  1469. nodeStatusUpdateFrequency: 5s
  1470. rotateCertificates: true
  1471. imageGCLowThresholdPercent: 70
  1472. imageGCHighThresholdPercent: 80
  1473. # 软驱逐阀值
  1474. evictionSoft:
  1475. imagefs.available: 15%
  1476. memory.available: 512Mi
  1477. nodefs.available: 15%
  1478. nodefs.inodesFree: 10%
  1479. # 达到软阈值之后,持续时间超过多久才进行驱逐
  1480. evictionSoftGracePeriod:
  1481. imagefs.available: 3m
  1482. memory.available: 1m
  1483. nodefs.available: 3m
  1484. nodefs.inodesFree: 1m
  1485. # 硬驱逐阀值
  1486. evictionHard:
  1487. imagefs.available: 10%
  1488. memory.available: 256Mi
  1489. nodefs.available: 10%
  1490. nodefs.inodesFree: 5%
  1491. evictionMaxPodGracePeriod: 30
  1492. # 节点资源预留
  1493. kubeReserved:
  1494. cpu: 200m\$(if [[ \$(cat /proc/meminfo | awk '/MemTotal/ {print \$2}') -gt 3670016 ]]; then echo -e '\n memory: 256Mi';fi)
  1495. ephemeral-storage: 1Gi
  1496. systemReserved:
  1497. cpu: 300m\$(if [[ \$(cat /proc/meminfo | awk '/MemTotal/ {print \$2}') -gt 3670016 ]]; then echo -e '\n memory: 512Mi';fi)
  1498. ephemeral-storage: 1Gi
  1499. kubeReservedCgroup: /kube.slice
  1500. systemReservedCgroup: /system.slice
  1501. enforceNodeAllocatable:
  1502. - pods
  1503. ---
  1504. apiVersion: kubeadm.k8s.io/v1beta2
  1505. kind: ClusterConfiguration
  1506. kubernetesVersion: $KUBE_VERSION
  1507. controlPlaneEndpoint: $KUBE_APISERVER:6443
  1508. networking:
  1509. dnsDomain: $KUBE_DNSDOMAIN
  1510. podSubnet: $KUBE_POD_SUBNET
  1511. serviceSubnet: $KUBE_SERVICE_SUBNET
  1512. imageRepository: $KUBE_IMAGE_REPO
  1513. apiServer:
  1514. certSANs:
  1515. - 127.0.0.1
  1516. - $KUBE_APISERVER
  1517. $(for h in $MASTER_NODES;do echo " - $h";done)
  1518. extraArgs:
  1519. event-ttl: '720h'
  1520. service-node-port-range: '30000-50000'
  1521. # 审计日志相关配置
  1522. audit-log-maxage: '20'
  1523. audit-log-maxbackup: '10'
  1524. audit-log-maxsize: '100'
  1525. audit-log-path: /var/log/kube-audit/audit.log
  1526. audit-policy-file: /etc/kubernetes/audit-policy.yaml
  1527. extraVolumes:
  1528. - name: audit-config
  1529. hostPath: /etc/kubernetes/audit-policy.yaml
  1530. mountPath: /etc/kubernetes/audit-policy.yaml
  1531. readOnly: true
  1532. pathType: File
  1533. - name: audit-log
  1534. hostPath: /var/log/kube-audit
  1535. mountPath: /var/log/kube-audit
  1536. pathType: DirectoryOrCreate
  1537. - name: localtime
  1538. hostPath: /etc/localtime
  1539. mountPath: /etc/localtime
  1540. readOnly: true
  1541. pathType: File
  1542. controllerManager:
  1543. extraArgs:
  1544. bind-address: 0.0.0.0
  1545. node-cidr-mask-size: '24'
  1546. deployment-controller-sync-period: '10s'
  1547. node-monitor-grace-period: '20s'
  1548. pod-eviction-timeout: '2m'
  1549. terminated-pod-gc-threshold: '30'
  1550. experimental-cluster-signing-duration: 87600h
  1551. feature-gates: RotateKubeletServerCertificate=true
  1552. extraVolumes:
  1553. - hostPath: /etc/localtime
  1554. mountPath: /etc/localtime
  1555. name: localtime
  1556. readOnly: true
  1557. pathType: File
  1558. scheduler:
  1559. extraArgs:
  1560. bind-address: 0.0.0.0
  1561. extraVolumes:
  1562. - hostPath: /etc/localtime
  1563. mountPath: /etc/localtime
  1564. name: localtime
  1565. readOnly: true
  1566. pathType: File
  1567. $(if [[ "${KUBE_VERSION}" == "1.21.1" ]]; then
  1568. echo "dns:
  1569. type: CoreDNS
  1570. imageRepository: docker.io
  1571. imageTag: 1.8.0"
  1572. fi)
  1573. EOF
  1574. "
  1575. check::exit_code "$?" "kubeadm init" "${MGMT_NODE}: set kubeadmcfg.yaml" "exit"
  1576. log::info "[kubeadm init]" "${MGMT_NODE}: kubeadm init start."
  1577. command::exec "${MGMT_NODE}" "kubeadm init --config=/etc/kubernetes/kubeadmcfg.yaml --upload-certs"
  1578. check::exit_code "$?" "kubeadm init" "${MGMT_NODE}: kubeadm init" "exit"
  1579. sleep 3
  1580. log::info "[kubeadm init]" "${MGMT_NODE}: set kube config."
  1581. command::exec "${MGMT_NODE}" "
  1582. mkdir -p \$HOME/.kube
  1583. sudo cp -f /etc/kubernetes/admin.conf \$HOME/.kube/config
  1584. "
  1585. check::exit_code "$?" "kubeadm init" "${MGMT_NODE}: set kube config" "exit"
  1586. if [[ "$(echo "$MASTER_NODES" | wc -w)" == "1" ]]; then
  1587. log::info "[kubeadm init]" "${MGMT_NODE}: delete master taint"
  1588. command::exec "${MGMT_NODE}" "kubectl taint nodes --all node-role.kubernetes.io/master-"
  1589. check::exit_code "$?" "kubeadm init" "${MGMT_NODE}: delete master taint"
  1590. fi
  1591. command::exec "${MGMT_NODE}" "
  1592. kubectl create clusterrolebinding node-client-auto-approve-csr --clusterrole=system:certificates.k8s.io:certificatesigningrequests:nodeclient --user=kubelet-bootstrap
  1593. kubectl create clusterrolebinding node-client-auto-renew-crt --clusterrole=system:certificates.k8s.io:certificatesigningrequests:selfnodeclient --group=system:nodes
  1594. kubectl create clusterrolebinding node-server-auto-renew-crt --clusterrole=system:certificates.k8s.io:certificatesigningrequests:selfnodeserver --group=system:nodes
  1595. "
  1596. check::exit_code "$?" "kubeadm init" "Auto-Approve kubelet cert csr" "exit"
  1597. }
  1598. # 加入集群
  1599. function kubeadm::join() {
  1600. log::info "[kubeadm join]" "master: get join token and cert info"
  1601. command::exec "${MGMT_NODE}" "
  1602. openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //'
  1603. "
  1604. get::command_output "CACRT_HASH" "$?" "exit"
  1605. command::exec "${MGMT_NODE}" "
  1606. kubeadm init phase upload-certs --upload-certs --config /etc/kubernetes/kubeadmcfg.yaml 2>> /dev/null | tail -1
  1607. "
  1608. get::command_output "INTI_CERTKEY" "$?" "exit"
  1609. command::exec "${MGMT_NODE}" "
  1610. kubeadm token create
  1611. "
  1612. get::command_output "INIT_TOKEN" "$?" "exit"
  1613. command::exec "${MGMT_NODE}" "
  1614. kubeadm config images list 2>/dev/null | awk -F: '/pause/ {print \$2}'
  1615. "
  1616. get::command_output "PAUSE_VERSION" "$?"
  1617. for host in $MASTER_NODES
  1618. do
  1619. [[ "${MGMT_NODE}" == "$host" ]] && continue
  1620. log::info "[kubeadm join]" "master $host join cluster."
  1621. command::exec "${host}" "
  1622. cat << EOF > /etc/kubernetes/kubeadmcfg.yaml
  1623. ---
  1624. apiVersion: kubeadm.k8s.io/v1beta2
  1625. kind: JoinConfiguration
  1626. discovery:
  1627. bootstrapToken:
  1628. apiServerEndpoint: $KUBE_APISERVER:6443
  1629. caCertHashes:
  1630. - sha256:${CACRT_HASH:-}
  1631. token: ${INIT_TOKEN}
  1632. timeout: 5m0s
  1633. controlPlane:
  1634. certificateKey: ${INTI_CERTKEY:-}
  1635. ${kubelet_nodeRegistration}
  1636. EOF
  1637. kubeadm join --config /etc/kubernetes/kubeadmcfg.yaml
  1638. "
  1639. check::exit_code "$?" "kubeadm join" "master $host join cluster"
  1640. log::info "[kubeadm join]" "$host: set kube config."
  1641. command::exec "${host}" "
  1642. mkdir -p \$HOME/.kube
  1643. sudo cp -f /etc/kubernetes/admin.conf \$HOME/.kube/config
  1644. "
  1645. check::exit_code "$?" "kubeadm join" "$host: set kube config" "exit"
  1646. command::exec "${host}" "
  1647. sed -i 's#.*$KUBE_APISERVER#127.0.0.1 $KUBE_APISERVER#g' /etc/hosts
  1648. "
  1649. done
  1650. for host in $WORKER_NODES
  1651. do
  1652. log::info "[kubeadm join]" "worker $host join cluster."
  1653. command::exec "${host}" "
  1654. mkdir -p /etc/kubernetes/manifests
  1655. cat << EOF > /etc/kubernetes/kubeadmcfg.yaml
  1656. ---
  1657. apiVersion: kubeadm.k8s.io/v1beta2
  1658. kind: JoinConfiguration
  1659. discovery:
  1660. bootstrapToken:
  1661. apiServerEndpoint: $KUBE_APISERVER:6443
  1662. caCertHashes:
  1663. - sha256:${CACRT_HASH:-}
  1664. token: ${INIT_TOKEN}
  1665. timeout: 5m0s
  1666. ${kubelet_nodeRegistration}
  1667. EOF
  1668. kubeadm join --config /etc/kubernetes/kubeadmcfg.yaml
  1669. "
  1670. check::exit_code "$?" "kubeadm join" "worker $host join cluster"
  1671. log::info "[kubeadm join]" "set $host worker node role."
  1672. command::exec "${MGMT_NODE}" "
  1673. kubectl get node --selector='!node-role.kubernetes.io/master' | grep '<none>' | awk '{print \"kubectl label node \" \$1 \" node-role.kubernetes.io/worker= --overwrite\" }' | bash
  1674. "
  1675. check::exit_code "$?" "kubeadm join" "set $host worker node role"
  1676. done
  1677. }
  1678. # 等待资源完成
  1679. function kube::wait() {
  1680. local app=$1
  1681. local namespace=$2
  1682. local resource=$3
  1683. local selector=${4:-}
  1684. sleep 3
  1685. log::info "[waiting]" "waiting $app"
  1686. command::exec "${MGMT_NODE}" "
  1687. $(declare -f utils::retry)
  1688. utils::retry 6 kubectl wait --namespace ${namespace} \
  1689. --for=condition=ready ${resource} \
  1690. --selector=$selector \
  1691. --timeout=60s
  1692. "
  1693. local status="$?"
  1694. check::exit_code "$status" "waiting" "$app ${resource} ready"
  1695. return "$status"
  1696. }
  1697. # 应用manifest
  1698. function kube::apply() {
  1699. local file=$1
  1700. log::info "[apply]" "$file"
  1701. command::exec "${MGMT_NODE}" "
  1702. $(declare -f utils::retry)
  1703. if [ -f \"$file\" ]; then
  1704. utils::retry 6 kubectl apply --wait=true --timeout=10s -f \"$file\"
  1705. else
  1706. utils::retry 6 \"cat <<EOF | kubectl apply --wait=true --timeout=10s -f -
  1707. \$(printf \"%s\" \"${2:-}\")
  1708. EOF
  1709. \"
  1710. fi
  1711. "
  1712. local status="$?"
  1713. check::exit_code "$status" "apply" "add $file" "exit"
  1714. return "$status"
  1715. }
  1716. # 集群状态
  1717. function kube::status() {
  1718. sleep 5
  1719. log::info "[cluster]" "cluster status"
  1720. command::exec "${MGMT_NODE}" "
  1721. echo
  1722. kubectl get node -o wide
  1723. echo
  1724. kubectl get pods -A
  1725. " && printf "%s" "${COMMAND_OUTPUT}"
  1726. }
  1727. # 添加或删除haproxy的后端server
  1728. function config::haproxy_backend() {
  1729. local action=${1:-add}
  1730. local action_cmd=""
  1731. local master_nodes
  1732. if [[ "$MASTER_NODES" == "" || "$MASTER_NODES" == "127.0.0.1" ]]; then
  1733. return
  1734. fi
  1735. command::exec "${MGMT_NODE}" "
  1736. kubectl get node --selector='node-role.kubernetes.io/master' -o jsonpath='{\$.items[*].status.addresses[?(@.type==\"InternalIP\")].address}'
  1737. "
  1738. get::command_output "master_nodes" "$?" "exit"
  1739. for m in $MASTER_NODES
  1740. do
  1741. if [[ "${action}" == "add" ]]; then
  1742. num=$(echo "${m}"| awk -F'.' '{print $4}')
  1743. action_cmd="${action_cmd}\necho \" server apiserver${num} ${m}:6443 check\" >> /etc/haproxy/haproxy.cfg"
  1744. else
  1745. [[ "${master_nodes}" == *"${m}"* ]] || return
  1746. action_cmd="${action_cmd}\n sed -i -e \"/${m}/d\" /etc/haproxy/haproxy.cfg"
  1747. fi
  1748. done
  1749. command::exec "${MGMT_NODE}" "
  1750. kubectl get node --selector='!node-role.kubernetes.io/master' -o jsonpath='{\$.items[*].status.addresses[?(@.type==\"InternalIP\")].address}'
  1751. "
  1752. get::command_output "worker_nodes" "$?"
  1753. for host in ${worker_nodes:-}
  1754. do
  1755. log::info "[config]" "worker ${host}: ${action} apiserver from haproxy"
  1756. command::exec "${host}" "
  1757. $(echo -ne "${action_cmd}")
  1758. haproxy -c -f /etc/haproxy/haproxy.cfg && systemctl reload haproxy
  1759. "
  1760. check::exit_code "$?" "config" "worker ${host}: ${action} apiserver(${m}) from haproxy"
  1761. done
  1762. }
  1763. # 更新 etcd 备份副本
  1764. function config::etcd_snapshot() {
  1765. command::exec "${MGMT_NODE}" "
  1766. count=\$(kubectl get node --selector='node-role.kubernetes.io/master' --no-headers | wc -l)
  1767. kubectl -n kube-system patch cronjobs etcd-snapshot --patch \"
  1768. spec:
  1769. jobTemplate:
  1770. spec:
  1771. completions: \${count:-1}
  1772. parallelism: \${count:-1}
  1773. \"
  1774. "
  1775. check::exit_code "$?" "config" "etcd-snapshot completions options"
  1776. }
  1777. # 获取命令的返回值
  1778. function get::command_output() {
  1779. local app="$1"
  1780. local status="$2"
  1781. local is_exit="${3:-}"
  1782. if [[ "$status" == "0" && "${COMMAND_OUTPUT}" != "" ]]; then
  1783. log::info "[command]" "get $app value succeeded."
  1784. eval "$app=\"${COMMAND_OUTPUT}\""
  1785. else
  1786. log::error "[command]" "get $app value failed."
  1787. [[ "$is_exit" == "exit" ]] && exit "$status"
  1788. fi
  1789. return "$status"
  1790. }
  1791. # 获取ingress连接地址
  1792. function get::ingress_conn() {
  1793. local port="${1:-80}"
  1794. local ingress_name="${2:-ingress-${KUBE_INGRESS}-controller}"
  1795. command::exec "${MGMT_NODE}" "
  1796. kubectl get node -o jsonpath='{range .items[*]}{ .status.addresses[?(@.type==\"InternalIP\")].address} {.status.conditions[?(@.status == \"True\")].status}{\"\\n\"}{end}' | awk '{if(\$2==\"True\")a=\$1}END{print a}'
  1797. "
  1798. get::command_output "node_ip" "$?"
  1799. command::exec "${MGMT_NODE}" "
  1800. kubectl get svc --all-namespaces -o go-template=\"{{range .items}}{{if eq .metadata.name \\\"${ingress_name}\\\"}}{{range.spec.ports}}{{if eq .port ${port}}}{{.nodePort}}{{end}}{{end}}{{end}}{{end}}\"
  1801. "
  1802. get::command_output "node_port" "$?"
  1803. INGRESS_CONN="${node_ip:-nodeIP}:${node_port:-nodePort}"
  1804. }
  1805. ######################################################################################################
  1806. # 主调用逻辑
  1807. ######################################################################################################
  1808. # 添加network组件
  1809. function add::network() {
  1810. if [[ "$KUBE_NETWORK" == "flannel" ]]; then
  1811. log::info "[network]" "add flannel"
  1812. local flannel_file="${OFFLINE_DIR}/manifests/kube-flannel.yml"
  1813. utils::download_file "https://cdn.jsdelivr.net/gh/coreos/flannel@v${FLANNEL_VERSION}/Documentation/kube-flannel.yml" "${flannel_file}"
  1814. command::exec "${MGMT_NODE}" "
  1815. sed -i -e 's#10.244.0.0/16#${KUBE_POD_SUBNET}#g' \
  1816. -e 's#quay.io/coreos#${KUBE_IMAGE_REPO}#g' \
  1817. -e 's#\"Type\": \"vxlan\"#\"Type\": \"${KUBE_FLANNEL_TYPE}\"#g' \"${flannel_file}\"
  1818. if [[ \"${KUBE_FLANNEL_TYPE}\" == \"vxlan\" ]]; then
  1819. sed -i 's#\"Type\": \"vxlan\"#\"Type\": \"vxlan\", \"DirectRouting\": true#g' \"${flannel_file}\"
  1820. fi
  1821. "
  1822. check::exit_code "$?" "flannel" "change flannel pod subnet"
  1823. kube::apply "${flannel_file}"
  1824. kube::wait "flannel" "kube-system" "pods" "app=flannel"
  1825. elif [[ "$KUBE_NETWORK" == "calico" ]]; then
  1826. log::info "[network]" "add calico"
  1827. utils::download_file "https://projectcalico.docs.tigera.io/archive/v${CALICO_VERSION%.*}/manifests/calico.yaml" "${OFFLINE_DIR}/manifests/calico.yaml"
  1828. utils::download_file "https://projectcalico.docs.tigera.io/archive/v${CALICO_VERSION%.*}/manifests/calicoctl.yaml" "${OFFLINE_DIR}/manifests/calicoctl.yaml"
  1829. command::exec "${MGMT_NODE}" "
  1830. sed -i \"s#:v.*#:v${CALICO_VERSION}#g\" \"${OFFLINE_DIR}/manifests/calico.yaml\"
  1831. sed -i 's#value: \"Always\"#value: \"CrossSubnet\"#g' \"${OFFLINE_DIR}/manifests/calico.yaml\"
  1832. sed -i \"s#:v.*#:v${CALICO_VERSION}#g\" \"${OFFLINE_DIR}/manifests/calicoctl.yaml\"
  1833. "
  1834. check::exit_code "$?" "network" "change calico version to ${CALICO_VERSION}"
  1835. kube::apply "${OFFLINE_DIR}/manifests/calico.yaml"
  1836. kube::apply "${OFFLINE_DIR}/manifests/calicoctl.yaml"
  1837. kube::wait "calico-kube-controllers" "kube-system" "pods" "k8s-app=calico-kube-controllers"
  1838. kube::wait "calico-node" "kube-system" "pods" "k8s-app=calico-node"
  1839. elif [[ "$KUBE_NETWORK" == "cilium" ]]; then
  1840. log::info "[network]" "add cilium"
  1841. local cilium_file="${OFFLINE_DIR}/manifests/cilium.yml"
  1842. local cilium_hubble_file="${OFFLINE_DIR}/manifests/cilium_hubble.yml"
  1843. utils::download_file "https://cdn.jsdelivr.net/gh/cilium/cilium@${CILIUM_VERSION}/install/kubernetes/quick-install.yaml" "${cilium_file}"
  1844. utils::download_file "https://cdn.jsdelivr.net/gh/cilium/cilium@${CILIUM_VERSION}/install/kubernetes/quick-hubble-install.yaml" "${cilium_hubble_file}"
  1845. local all_node=""
  1846. if [[ "${MASTER_NODES}" == "" && "${WORKER_NODES}" == "" ]]; then
  1847. command::exec "${MGMT_NODE}" "
  1848. kubectl get node -o jsonpath='{range.items[*]}{.status.addresses[?(@.type==\"InternalIP\")].address} {end}'
  1849. "
  1850. get::command_output "all_node" "$?"
  1851. else
  1852. all_node="${MASTER_NODES} ${WORKER_NODES}"
  1853. fi
  1854. for host in $all_node
  1855. do
  1856. command::exec "${host}" "mount bpffs -t bpf /sys/fs/bpf"
  1857. check::exit_code "$?" "network" "${host}: mount bpf filesystem"
  1858. done
  1859. command::exec "${MGMT_NODE}" "
  1860. sed -i \"s#10.0.0.0/8#${KUBE_POD_SUBNET}#g\" \"${cilium_file}\"
  1861. "
  1862. kube::apply "${cilium_file}"
  1863. kube::wait "cilium-node" "kube-system" "pods" "k8s-app=cilium"
  1864. kube::wait "cilium-operator" "kube-system" "pods" "name=cilium-operator"
  1865. kube::apply "${cilium_hubble_file}"
  1866. kube::wait "hubble-relay" "kube-system" "pods" "k8s-app=hubble-relay"
  1867. log::info "[monitor]" "add hubble-ui ingress"
  1868. kube::apply "hubble-ui ingress" "
  1869. ---
  1870. apiVersion: networking.k8s.io/v1
  1871. kind: Ingress
  1872. metadata:
  1873. name: hubble-ui
  1874. namespace: kube-system
  1875. annotations:
  1876. kubernetes.io/ingress.class: ${KUBE_INGRESS}
  1877. spec:
  1878. rules:
  1879. - host: hubble-ui.cluster.local
  1880. http:
  1881. paths:
  1882. - path: /
  1883. pathType: Prefix
  1884. backend:
  1885. service:
  1886. name: hubble-ui
  1887. port:
  1888. number: 80
  1889. "
  1890. # shellcheck disable=SC2181
  1891. if [[ "$?" == "0" ]]; then
  1892. get::ingress_conn
  1893. log::access "[ingress]" "curl -H 'Host:hubble-ui.cluster.local' http://${INGRESS_CONN}"
  1894. fi
  1895. else
  1896. log::warning "[network]" "No $KUBE_NETWORK config."
  1897. fi
  1898. }
  1899. # 添加ingress组件
  1900. function add::ingress() {
  1901. # 安装 ingress-nginx
  1902. log::info "[ingress]" "add ingress-nginx"
  1903. command::exec "${MGMT_NODE}" "
  1904. $(declare -f utils::retry)
  1905. helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
  1906. utils::retry 6 helm install ingress-nginx ingress-nginx/ingress-nginx \
  1907. --namespace ingress-nginx --create-namespace \
  1908. --version ${INGRESS_NGINX} \
  1909. --set controller.admissionWebhooks.patch.image.registry=registry.hub.docker.com \
  1910. --set controller.admissionWebhooks.patch.image.image=k8sgcrioingressnginx/kube-webhook-certgen \
  1911. --set controller.admissionWebhooks.patch.image.digest= \
  1912. --set controller.admissionWebhooks.enabled=true \
  1913. --set controller.admissionWebhooks.extraEnvs\[0\].name=\"TZ\" \
  1914. --set controller.admissionWebhooks.extraEnvs\[0\].value=\"Asia/Shanghai\" \
  1915. --set controller.kind=DaemonSet \
  1916. --set controller.replicaCount=1 \
  1917. --set controller.minAvailable=1 \
  1918. --set controller.image.registry=registry.hub.docker.com \
  1919. --set controller.image.image=k8sgcrioingressnginx/controller \
  1920. --set controller.image.digest= \
  1921. --set controller.ingressClassResource.name=nginx \
  1922. --set controller.ingressClassResource.enable=true \
  1923. --set controller.ingressClassResource.default=false \
  1924. --set controller.service.enabled=true \
  1925. --set controller.service.type=NodePort \
  1926. --set controller.service.enableHttp=true \
  1927. --set controller.service.enableHttps=true \
  1928. --set controller.service.nodePorts.http=30080 \
  1929. --set controller.service.nodePorts.https=30443 \
  1930. --set controller.extraEnvs\[0\].name=\"TZ\" \
  1931. --set controller.extraEnvs\[0\].value=\"Asia/Shanghai\" \
  1932. --set defaultBackend.image.registry=registry.hub.docker.com \
  1933. --set defaultBackend.image.image=gcmirrors/defaultbackend-amd64 \
  1934. --set defaultBackend.enabled=true \
  1935. --set defaultBackend.name=defaultbackend \
  1936. --set defaultBackend.replicaCount=1 \
  1937. --set defaultBackend.minAvailable=1 \
  1938. --set defaultBackend.extraEnvs\[0\].name=\"TZ\" \
  1939. --set defaultBackend.extraEnvs\[0\].value=\"Asia/Shanghai\" \
  1940. --set rbac.create=true \
  1941. --set serviceAccount.create=true \
  1942. --set podSecurityPolicy.enabled=true
  1943. kubectl get pod -n ingress-nginx -o wide
  1944. kubectl get svc -n ingress-nginx -o wide
  1945. "
  1946. # 安装 nginx
  1947. log::info "[nginx]" "add nginx"
  1948. command::exec "${MGMT_NODE}" "
  1949. sudo yum -y install nginx
  1950. nginx -v
  1951. sudo systemctl enable nginx
  1952. sudo service nginx start
  1953. cat << EOF > /etc/nginx/conf.d/k8s.ingress.conf
  1954. upstream k8s-ingress {
  1955. $(for h in $MASTER_NODES $WORKER_NODES;do echo " server $h:30080 max_fails=1 fail_timeout=15s;";done)
  1956. keepalive 128;
  1957. }
  1958. server {
  1959. listen ${NGINX_HTTP_PORT};
  1960. location / {
  1961. proxy_http_version 1.1;
  1962. proxy_set_header Connection \"\";
  1963. proxy_next_upstream error;
  1964. proxy_set_header X-Real-IP \\\$remote_addr;
  1965. proxy_set_header X-Forwarded-For \\\$proxy_add_x_forwarded_for;
  1966. proxy_set_header Host \\\$http_host;
  1967. proxy_set_header X-Nginx-Proxy true;
  1968. proxy_pass http://k8s-ingress/;
  1969. }
  1970. }
  1971. EOF
  1972. sudo nginx -s reload
  1973. "
  1974. }
  1975. # 添加addon组件
  1976. function add::addon() {
  1977. # TODO add addon
  1978. log::warning "[TODO]" "add addon"
  1979. }
  1980. # 添加监控组件
  1981. function add::monitor() {
  1982. # TODO add monitor
  1983. log::warning "[TODO]" "add monitor"
  1984. }
  1985. # 添加log组件
  1986. function add::log() {
  1987. # TODO add log
  1988. log::warning "[TODO]" "add log"
  1989. }
  1990. # 添加存储
  1991. function add::storage() {
  1992. # TODO add storage
  1993. log::warning "[TODO]" "add storage"
  1994. }
  1995. # 添加用户界面
  1996. function add::ui() {
  1997. local path="/tmp"
  1998. # 安装 rancher
  1999. log::info "[rancher]" "add rancher"
  2000. command::exec "${MGMT_NODE}" "
  2001. $(declare -f utils::retry)
  2002. cd ${path}
  2003. helm repo add rancher-stable http://rancher-mirror.oss-cn-beijing.aliyuncs.com/server-charts/stable
  2004. utils::retry 6 helm pull rancher-stable/rancher --version ${RANCHER_VERSION} --untar
  2005. cat << EOF > rancher/templates/service.yaml
  2006. apiVersion: v1
  2007. kind: Service
  2008. metadata:
  2009. name: {{ template \"rancher.fullname\" . }}
  2010. labels:
  2011. {{ include \"rancher.labels\" . | indent 4 }}
  2012. spec:
  2013. type: NodePort
  2014. ports:
  2015. - port: 80
  2016. targetPort: 80
  2017. protocol: TCP
  2018. name: http
  2019. # 使用nodePort端口
  2020. nodePort: 31080
  2021. - port: 443
  2022. targetPort: 444
  2023. protocol: TCP
  2024. name: https-internal
  2025. # 使用nodePort端口
  2026. nodePort: 31443
  2027. selector:
  2028. app: {{ template \"rancher.fullname\" . }}
  2029. EOF
  2030. helm install rancher ./rancher \
  2031. --namespace cattle-system --create-namespace \
  2032. --set replicas=1 \
  2033. --set extraEnv\[0\].name=\"TZ\" \
  2034. --set extraEnv\[0\].value=\"Asia/Shanghai\" \
  2035. --set ingress.tls.source=secret \
  2036. --set ingress.enabled=false
  2037. "
  2038. log::info "[rancher]" "获取初始密码 kubectl get secret --namespace cattle-system bootstrap-secret -o go-template='{{.data.bootstrapPassword|base64decode}}{{ \"\n\" }}'"
  2039. log::info "[rancher]" "重置初始密码 kubectl -n cattle-system exec \$(kubectl -n cattle-system get pods -l app=rancher | grep '1/1' | head -1 | awk '{ print \$1 }') -- reset-password"
  2040. }
  2041. # 运维操作
  2042. function add::ops() {
  2043. local master_num
  2044. master_num=$(awk '{print NF}' <<< "${MASTER_NODES}")
  2045. log::info "[ops]" "add anti-affinity strategy to coredns"
  2046. command::exec "${MGMT_NODE}" """
  2047. kubectl -n kube-system patch deployment coredns --patch '{\"spec\": {\"template\": {\"spec\": {\"affinity\":{\"podAntiAffinity\":{\"preferredDuringSchedulingIgnoredDuringExecution\":[{\"weight\":100,\"podAffinityTerm\":{\"labelSelector\":{\"matchExpressions\":[{\"key\":\"k8s-app\",\"operator\":\"In\",\"values\":[\"kube-dns\"]}]},\"topologyKey\":\"kubernetes.io/hostname\"}}]}}}}}}' --record
  2048. """
  2049. check::exit_code "$?" "ops" "add anti-affinity strategy to coredns"
  2050. log::info "[ops]" "add etcd snapshot cronjob"
  2051. command::exec "${MGMT_NODE}" "
  2052. kubeadm config images list --config=/etc/kubernetes/kubeadmcfg.yaml 2>/dev/null | grep etcd:
  2053. "
  2054. get::command_output "etcd_image" "$?"
  2055. command::exec "${MGMT_NODE}" "
  2056. kubectl get node --selector='node-role.kubernetes.io/master' --no-headers | wc -l
  2057. "
  2058. get::command_output "master_num" "$?"
  2059. [[ "${master_num:-0}" == "0" ]] && master_num=1
  2060. kube::apply "etcd-snapshot" """
  2061. ---
  2062. apiVersion: batch/v1beta1
  2063. kind: CronJob
  2064. metadata:
  2065. name: etcd-snapshot
  2066. namespace: kube-system
  2067. spec:
  2068. schedule: '0 */6 * * *'
  2069. successfulJobsHistoryLimit: 3
  2070. suspend: false
  2071. concurrencyPolicy: Allow
  2072. failedJobsHistoryLimit: 3
  2073. jobTemplate:
  2074. spec:
  2075. backoffLimit: 6
  2076. parallelism: ${master_num}
  2077. completions: ${master_num}
  2078. template:
  2079. metadata:
  2080. labels:
  2081. app: etcd-snapshot
  2082. spec:
  2083. affinity:
  2084. podAntiAffinity:
  2085. requiredDuringSchedulingIgnoredDuringExecution:
  2086. - labelSelector:
  2087. matchExpressions:
  2088. - key: app
  2089. operator: In
  2090. values:
  2091. - etcd-snapshot
  2092. topologyKey: 'kubernetes.io/hostname'
  2093. containers:
  2094. - name: etcd-snapshot
  2095. image: ${etcd_image:-${KUBE_IMAGE_REPO}/etcd:3.4.13-0}
  2096. imagePullPolicy: IfNotPresent
  2097. args:
  2098. - -c
  2099. - etcdctl --endpoints=https://127.0.0.1:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt
  2100. --cert=/etc/kubernetes/pki/etcd/healthcheck-client.crt --key=/etc/kubernetes/pki/etcd/healthcheck-client.key
  2101. snapshot save /backup/etcd-snapshot-\\\\\\\$(date +%Y-%m-%d_%H:%M:%S_%Z).db
  2102. && echo 'delete old backups' && { find /backup -type f -mtime +30 -exec rm -fv {} \\; || echo error; }
  2103. command:
  2104. - /usr/bin/bash
  2105. env:
  2106. - name: ETCDCTL_API
  2107. value: '3'
  2108. resources: {}
  2109. terminationMessagePath: /dev/termination-log
  2110. terminationMessagePolicy: File
  2111. volumeMounts:
  2112. - name: etcd-certs
  2113. mountPath: /etc/kubernetes/pki/etcd
  2114. readOnly: true
  2115. - name: backup
  2116. mountPath: /backup
  2117. - name: etc
  2118. mountPath: /etc
  2119. - name: bin
  2120. mountPath: /usr/bin
  2121. - name: lib64
  2122. mountPath: /lib64
  2123. dnsPolicy: ClusterFirst
  2124. hostNetwork: true
  2125. nodeSelector:
  2126. node-role.kubernetes.io/master: ''
  2127. tolerations:
  2128. - effect: NoSchedule
  2129. operator: Exists
  2130. restartPolicy: OnFailure
  2131. schedulerName: default-scheduler
  2132. securityContext: {}
  2133. terminationGracePeriodSeconds: 30
  2134. volumes:
  2135. - name: etcd-certs
  2136. hostPath:
  2137. path: /etc/kubernetes/pki/etcd
  2138. type: DirectoryOrCreate
  2139. - name: backup
  2140. hostPath:
  2141. path: /var/lib/etcd/backups
  2142. type: DirectoryOrCreate
  2143. - name: etc
  2144. hostPath:
  2145. path: /etc
  2146. - name: bin
  2147. hostPath:
  2148. path: /usr/bin
  2149. - name: lib64
  2150. hostPath:
  2151. path: /lib64
  2152. """
  2153. # shellcheck disable=SC2181
  2154. [[ "$?" == "0" ]] && log::access "[ops]" "etcd backup directory: /var/lib/etcd/backups"
  2155. command::exec "${MGMT_NODE}" "
  2156. jobname=\"etcd-snapshot-$(date +%s)\"
  2157. kubectl create job --from=cronjob/etcd-snapshot \${jobname} -n kube-system && \
  2158. kubectl wait --for=condition=complete job/\${jobname} -n kube-system
  2159. "
  2160. check::exit_code "$?" "ops" "trigger etcd backup"
  2161. }
  2162. # 重置节点
  2163. function reset::node() {
  2164. local host=$1
  2165. log::info "[reset]" "node $host"
  2166. command::exec "${host}" "
  2167. set +ex
  2168. cri_socket=\"\"
  2169. [ -S /var/run/crio/crio.sock ] && cri_socket=\"--cri-socket /var/run/crio/crio.sock\"
  2170. [ -S /run/containerd/containerd.sock ] && cri_socket=\"--cri-socket /run/containerd/containerd.sock\"
  2171. kubeadm reset -f \$cri_socket
  2172. [ -f \"\$(which kubelet)\" ] && { systemctl stop kubelet; find /var/lib/kubelet | xargs -n 1 findmnt -n -o TARGET -T | sort | uniq | xargs -r umount -v; yum remove -y kubeadm kubelet kubectl; }
  2173. [ -d /etc/kubernetes ] && rm -rf /etc/kubernetes/* /var/lib/kubelet/* /var/lib/etcd/* \$HOME/.kube /etc/cni/net.d/* /var/lib/dockershim/* /var/lib/cni/* /var/run/kubernetes/*
  2174. [ -f \"\$(which docker)\" ] && { docker rm -f -v \$(docker ps | grep kube | awk '{print \$1}'); systemctl stop docker; rm -rf \$HOME/.docker /etc/docker/* /var/lib/docker/*; yum remove -y docker; }
  2175. [ -f \"\$(which containerd)\" ] && { crictl rm \$(crictl ps -a -q); systemctl stop containerd; rm -rf /etc/containerd/* /var/lib/containerd/*; yum remove -y containerd.io; }
  2176. [ -f \"\$(which crio)\" ] && { crictl rm \$(crictl ps -a -q); systemctl stop crio; rm -rf /etc/crictl.yaml /etc/crio/* /var/run/crio/*; yum remove -y cri-o; }
  2177. [ -f \"\$(which runc)\" ] && { find /run/containers/ /var/lib/containers/ | xargs -n 1 findmnt -n -o TARGET -T | sort | uniq | xargs -r umount -v; rm -rf /var/lib/containers/* /var/run/containers/*; yum remove -y runc; }
  2178. [ -f \"\$(which haproxy)\" ] && { systemctl stop haproxy; rm -rf /etc/haproxy/*; yum remove -y haproxy; }
  2179. sed -i -e \"/$KUBE_APISERVER/d\" -e '/-worker-/d' -e '/-master-/d' /etc/hosts
  2180. sed -i '/## Kainstall managed start/,/## Kainstall managed end/d' /etc/security/limits.conf /etc/systemd/system.conf /etc/bashrc /etc/rc.local /etc/audit/rules.d/audit.rules
  2181. [ -d /var/lib/elasticsearch ] && rm -rf /var/lib/elasticsearch/*
  2182. [ -d /var/lib/longhorn ] && rm -rf /var/lib/longhorn/*
  2183. [ -d \"${OFFLINE_DIR:-/tmp/abc}\" ] && rm -rf \"${OFFLINE_DIR:-/tmp/abc}\"
  2184. for repo in kubernetes.repo docker-ce.repo devel_kubic_libcontainers_stable.repo elrepo.repo
  2185. do
  2186. [ -f /etc/yum.repos.d/\${repo} ] && rm -f /etc/yum.repos.d/\${repo}
  2187. done
  2188. ipvsadm --clear
  2189. iptables -F && iptables -t nat -F && iptables -t mangle -F && iptables -X
  2190. for int in kube-ipvs0 cni0 docker0 dummy0 flannel.1 cilium_host cilium_net cilium_vxlan lxc_health nodelocaldns
  2191. do
  2192. [ -d /sys/class/net/\${int} ] && ip link delete \${int}
  2193. done
  2194. modprobe -r ipip
  2195. echo done.
  2196. "
  2197. check::exit_code "$?" "reset" "$host: reset"
  2198. }
  2199. # 重置所有节点
  2200. function reset::cluster() {
  2201. local all_node=""
  2202. command::exec "${MGMT_NODE}" "
  2203. kubectl get node -o jsonpath='{range.items[*]}{.status.addresses[?(@.type==\"InternalIP\")].address} {end}'
  2204. "
  2205. get::command_output "all_node" "$?"
  2206. all_node=$(echo "${WORKER_NODES} ${MASTER_NODES} ${all_node}" | awk '{for (i=1;i<=NF;i++) if (!a[$i]++) printf("%s%s",$i,FS)}')
  2207. for host in $all_node
  2208. do
  2209. reset::node "$host"
  2210. done
  2211. }
  2212. # 节点加载离线包
  2213. function offline::load() {
  2214. local role="${1:-}"
  2215. local hosts=""
  2216. if [[ "${role}" == "master" ]]; then
  2217. hosts="${MASTER_NODES}"
  2218. elif [[ "${role}" == "worker" ]]; then
  2219. hosts="${WORKER_NODES}"
  2220. fi
  2221. for host in ${hosts}
  2222. do
  2223. log::info "[offline]" "${role} ${host}: load offline file"
  2224. command::exec "${host}" "[[ ! -d \"${OFFLINE_DIR}\" ]] && { mkdir -pv \"${OFFLINE_DIR}\"; chmod 777 \"${OFFLINE_DIR}\"; } ||:"
  2225. check::exit_code "$?" "offline" "$host: mkdir offline dir" "exit"
  2226. if [[ "${UPGRADE_KERNEL_TAG:-}" == "1" ]]; then
  2227. command::scp "${host}" "${TMP_DIR}/packages/kernel/*" "${OFFLINE_DIR}"
  2228. check::exit_code "$?" "offline" "scp kernel file to $host" "exit"
  2229. else
  2230. log::info "[offline]" "${role} ${host}: copy offline file"
  2231. command::scp "${host}" "${TMP_DIR}/packages/kubeadm/*" "${OFFLINE_DIR}"
  2232. check::exit_code "$?" "offline" "scp kube file to $host" "exit"
  2233. command::scp "${host}" "${TMP_DIR}/packages/all/*" "${OFFLINE_DIR}"
  2234. check::exit_code "$?" "offline" "scp all file to $host" "exit"
  2235. if [[ "${role}" == "worker" ]]; then
  2236. command::scp "${host}" "${TMP_DIR}/packages/worker/*" "${OFFLINE_DIR}"
  2237. check::exit_code "$?" "offline" "scp worker file to $host" "exit"
  2238. fi
  2239. command::scp "${host}" "${TMP_DIR}/images/${role}.tgz" "${OFFLINE_DIR}"
  2240. check::exit_code "$?" "offline" "scp ${role} images to $host" "exit"
  2241. command::scp "${host}" "${TMP_DIR}/images/all.tgz" "${OFFLINE_DIR}"
  2242. check::exit_code "$?" "offline" "scp all images to $host" "exit"
  2243. fi
  2244. log::info "[offline]" "${role} ${host}: install package"
  2245. command::exec "${host}" "yum localinstall -y --skip-broken ${OFFLINE_DIR}/*.rpm"
  2246. check::exit_code "$?" "offline" "${role} ${host}: install package" "exit"
  2247. if [[ "${UPGRADE_KERNEL_TAG:-}" != "1" ]]; then
  2248. command::exec "${host}" "
  2249. set -e
  2250. for target in firewalld python-firewall firewalld-filesystem iptables; do
  2251. systemctl stop \$target &>/dev/null || true
  2252. systemctl disable \$target &>/dev/null || true
  2253. done
  2254. systemctl start docker && \
  2255. cd ${OFFLINE_DIR} && \
  2256. gzip -d -c ${1}.tgz | docker load && gzip -d -c all.tgz | docker load
  2257. "
  2258. check::exit_code "$?" "offline" "$host: load images" "exit"
  2259. fi
  2260. command::exec "${host}" "rm -rf ${OFFLINE_DIR:-/tmp/abc}"
  2261. check::exit_code "$?" "offline" "$host: clean offline file"
  2262. done
  2263. command::scp "${MGMT_NODE}" "${TMP_DIR}/manifests" "${OFFLINE_DIR}"
  2264. check::exit_code "$?" "offline" "scp manifests file to ${MGMT_NODE}" "exit"
  2265. command::scp "${MGMT_NODE}" "${TMP_DIR}/bins" "${OFFLINE_DIR}"
  2266. check::exit_code "$?" "offline" "scp bins file to ${MGMT_NODE}" "exit"
  2267. }
  2268. # 集群节点加载离线包
  2269. function offline::cluster() {
  2270. [ ! -f "${OFFLINE_FILE}" ] && { log::error "[offline]" "not found ${OFFLINE_FILE}" ; exit 1; }
  2271. log::info "[offline]" "Unzip offline package on local."
  2272. tar zxf "${OFFLINE_FILE}" -C "${TMP_DIR}/"
  2273. check::exit_code "$?" "offline" "Unzip offline package"
  2274. offline::load "master"
  2275. offline::load "worker"
  2276. }
  2277. # 初始化集群
  2278. function init::cluster() {
  2279. MGMT_NODE=$(echo "${MASTER_NODES}" | awk '{print $1}')
  2280. # 加载离线包
  2281. [[ "${OFFLINE_TAG:-}" == "1" ]] && offline::cluster
  2282. # 1. 初始化节点
  2283. init::node
  2284. # 2. 安装包
  2285. install::package
  2286. # 3. 初始化kubeadm
  2287. kubeadm::init
  2288. # 4. 加入集群
  2289. kubeadm::join
  2290. # 5. 添加network
  2291. add::network
  2292. # 6. 安装addon
  2293. add::addon
  2294. # 7. 添加ingress
  2295. add::ingress
  2296. # 8. 添加storage
  2297. [[ "${STORAGE_TAG:-}" == "1" ]] && add::storage
  2298. # 9. 添加web ui
  2299. add::ui
  2300. # 10. 添加monitor
  2301. [[ "${MONITOR_TAG:-}" == "1" ]] && add::monitor
  2302. # 11. 添加log
  2303. [[ "${LOG_TAG:-}" == "1" ]] && add::log
  2304. # 12. 运维操作
  2305. add::ops
  2306. # 13. 查看集群状态
  2307. kube::status
  2308. }
  2309. # 添加节点
  2310. function add::node() {
  2311. # 加载离线包
  2312. [[ "${OFFLINE_TAG:-}" == "1" ]] && offline::cluster
  2313. # KUBE_VERSION未指定时,获取集群的版本
  2314. if [[ "${KUBE_VERSION}" == "" || "${KUBE_VERSION}" == "latest" ]]; then
  2315. command::exec "${MGMT_NODE}" "
  2316. kubectl get node --selector='node-role.kubernetes.io/master' -o jsonpath='{range.items[*]}{.status.nodeInfo.kubeletVersion } {end}' | awk -F'v| ' '{print \$2}'
  2317. "
  2318. get::command_output "KUBE_VERSION" "$?" "exit"
  2319. fi
  2320. # 1. 初始化节点
  2321. init::add_node
  2322. # 2. 安装包
  2323. install::package
  2324. # 3. 加入集群
  2325. kubeadm::join
  2326. # 4. haproxy添加apiserver
  2327. config::haproxy_backend "add"
  2328. # 5. 更新 etcd snapshot 副本
  2329. config::etcd_snapshot
  2330. # 6. 查看集群状态
  2331. kube::status
  2332. }
  2333. # 删除节点
  2334. function del::node() {
  2335. config::haproxy_backend "remove"
  2336. local cluster_nodes=""
  2337. local del_hosts_cmd=""
  2338. command::exec "${MGMT_NODE}" "
  2339. kubectl get node -o jsonpath='{range.items[*]}{.status.addresses[?(@.type==\"InternalIP\")].address} {.metadata.name }\\n{end}'
  2340. "
  2341. get::command_output "cluster_nodes" "$?" exit
  2342. for host in $MASTER_NODES
  2343. do
  2344. command::exec "${MGMT_NODE}" "
  2345. etcd_pod=\$(kubectl -n kube-system get pods -l component=etcd --field-selector=status.phase=Running -o jsonpath='{\$.items[0].metadata.name}')
  2346. etcd_node=\$(kubectl -n kube-system exec \$etcd_pod -- sh -c \"export ETCDCTL_API=3 ETCDCTL_CACERT=/etc/kubernetes/pki/etcd/ca.crt ETCDCTL_CERT=/etc/kubernetes/pki/etcd/server.crt ETCDCTL_KEY=/etc/kubernetes/pki/etcd/server.key ETCDCTL_ENDPOINTS=https://127.0.0.1:2379; etcdctl member list\"| grep $host | awk -F, '{print \$1}')
  2347. echo \"\$etcd_pod \$etcd_node\"
  2348. kubectl -n kube-system exec \$etcd_pod -- sh -c \"export ETCDCTL_API=3 ETCDCTL_CACERT=/etc/kubernetes/pki/etcd/ca.crt ETCDCTL_CERT=/etc/kubernetes/pki/etcd/server.crt ETCDCTL_KEY=/etc/kubernetes/pki/etcd/server.key ETCDCTL_ENDPOINTS=https://127.0.0.1:2379; etcdctl member remove \$etcd_node; etcdctl member list\"
  2349. "
  2350. check::exit_code "$?" "del" "remove $host etcd member"
  2351. done
  2352. for host in $MASTER_NODES $WORKER_NODES
  2353. do
  2354. log::info "[del]" "node $host"
  2355. local node_name; node_name=$(echo -ne "${cluster_nodes}" | grep "${host}" | awk '{print $2}')
  2356. if [[ "${node_name}" == "" ]]; then
  2357. log::warning "[del]" "node $host not found."
  2358. read -r -t 10 -n 1 -p "Do you need to reset the node (y/n)? " answer
  2359. [[ -z "$answer" || "$answer" != "y" ]] && exit || echo
  2360. else
  2361. log::info "[del]" "drain $host"
  2362. command::exec "${MGMT_NODE}" "kubectl drain $node_name --force --ignore-daemonsets --delete-local-data"
  2363. check::exit_code "$?" "del" "$host: drain"
  2364. log::info "[del]" "delete node $host"
  2365. command::exec "${MGMT_NODE}" "kubectl delete node $node_name"
  2366. check::exit_code "$?" "del" "$host: delete"
  2367. sleep 3
  2368. fi
  2369. reset::node "$host"
  2370. del_hosts_cmd="${del_hosts_cmd}\nsed -i "/$host/d" /etc/hosts"
  2371. done
  2372. for host in $(echo -ne "${cluster_nodes}" | awk '{print $1}')
  2373. do
  2374. log::info "[del]" "$host: remove del node hostname resolution"
  2375. command::exec "${host}" "
  2376. $(echo -ne "${del_hosts_cmd}")
  2377. "
  2378. check::exit_code "$?" "del" "remove del node hostname resolution"
  2379. done
  2380. [ "$MASTER_NODES" != "" ] && config::etcd_snapshot
  2381. kube::status
  2382. }
  2383. # 升级集群
  2384. function upgrade::cluster() {
  2385. log::info "[upgrade]" "upgrade to $KUBE_VERSION"
  2386. log::info "[upgrade]" "backup cluster"
  2387. add::ops
  2388. local stable_version="2"
  2389. command::exec "127.0.0.1" "wget https://storage.googleapis.com/kubernetes-release/release/stable.txt -q -O -"
  2390. get::command_output "stable_version" "$?" && stable_version="${stable_version#v}"
  2391. local node_hosts="$MASTER_NODES $WORKER_NODES"
  2392. if [[ "$node_hosts" == " " ]]; then
  2393. command::exec "${MGMT_NODE}" "
  2394. kubectl get node -o jsonpath='{range.items[*]}{.metadata.name } {end}'
  2395. "
  2396. get::command_output "node_hosts" "$?" exit
  2397. fi
  2398. local skip_plan=${SKIP_UPGRADE_PLAN,,}
  2399. for host in ${node_hosts}
  2400. do
  2401. log::info "[upgrade]" "node: $host"
  2402. local local_version=""
  2403. command::exec "${host}" "kubectl version --client --short | awk '{print \$3}'"
  2404. get::command_output "local_version" "$?" && local_version="${local_version#v}"
  2405. if [[ "${KUBE_VERSION}" != "latest" ]]; then
  2406. if [[ "${KUBE_VERSION}" == "${local_version}" ]];then
  2407. log::warning "[check]" "The specified version(${KUBE_VERSION}) is consistent with the local version(${local_version})!"
  2408. continue
  2409. fi
  2410. if [[ $(utils::version_to_number "$KUBE_VERSION") -lt $(utils::version_to_number "${local_version}") ]];then
  2411. log::warning "[check]" "The specified version($KUBE_VERSION) is less than the local version(${local_version})!"
  2412. continue
  2413. fi
  2414. if [[ $(utils::version_to_number "$KUBE_VERSION") -gt $(utils::version_to_number "${stable_version}") ]];then
  2415. log::warning "[check]" "The specified version($KUBE_VERSION) is more than the stable version(${stable_version})!"
  2416. continue
  2417. fi
  2418. else
  2419. if [[ $(utils::version_to_number "${local_version}") -ge $(utils::version_to_number "${stable_version}") ]];then
  2420. log::warning "[check]" "The local version($local_version) is greater or equal to the stable version(${stable_version})!"
  2421. continue
  2422. fi
  2423. fi
  2424. command::exec "${MGMT_NODE}" "kubectl drain ${host} --ignore-daemonsets --delete-local-data"
  2425. check::exit_code "$?" "upgrade" "drain ${host} node" "exit"
  2426. sleep 5
  2427. if [[ "${skip_plan}" == "false" ]]; then
  2428. command::exec "${host}" "$(declare -f script::upgrage_kube); script::upgrage_kube 'init' '$KUBE_VERSION'"
  2429. check::exit_code "$?" "upgrade" "plan and upgrade cluster on ${host}" "exit"
  2430. command::exec "${host}" "$(declare -f utils::retry); utils::retry 10 kubectl get node"
  2431. check::exit_code "$?" "upgrade" "${host}: upgrade" "exit"
  2432. skip_plan=true
  2433. else
  2434. command::exec "${host}" "$(declare -f script::upgrage_kube); script::upgrage_kube 'node' '$KUBE_VERSION'"
  2435. check::exit_code "$?" "upgrade" "upgrade ${host} node" "exit"
  2436. fi
  2437. command::exec "${MGMT_NODE}" "kubectl wait --for=condition=Ready node/${host} --timeout=120s"
  2438. check::exit_code "$?" "upgrade" "${host} ready"
  2439. sleep 5
  2440. command::exec "${MGMT_NODE}" "$(declare -f utils::retry); utils::retry 6 kubectl uncordon ${host}"
  2441. check::exit_code "$?" "upgrade" "uncordon ${host} node"
  2442. sleep 5
  2443. done
  2444. kube::status
  2445. }
  2446. # 脚本文件更新
  2447. function update::self() {
  2448. log::info "[update]" "download kainstall script to $0"
  2449. command::exec "127.0.0.1" "
  2450. wget --timeout=10 --waitretry=3 --tries=5 --retry-connrefused https://cdn.jsdelivr.net/gh/lework/kainstall@master/kainstall-centos.sh -O /tmp/kainstall-centos.sh || exit 1
  2451. /bin/mv -fv /tmp/kainstall-centos.sh \"$0\"
  2452. chmod +x \"$0\"
  2453. "
  2454. check::exit_code "$?" "update" "kainstall script"
  2455. }
  2456. # 数据处理及限制
  2457. function transform::data() {
  2458. MASTER_NODES=$(echo "${MASTER_NODES}" | tr ',' ' ')
  2459. WORKER_NODES=$(echo "${WORKER_NODES}" | tr ',' ' ')
  2460. if ! utils::is_element_in_array "$KUBE_CRI" docker containerd cri-o ; then
  2461. log::error "[limit]" "$KUBE_CRI is not supported, only [docker,containerd,cri-o]"
  2462. exit 1
  2463. fi
  2464. [[ "$KUBE_CRI" != "docker" && "${OFFLINE_TAG:-}" == "1" ]] && { log::error "[limit]" "$KUBE_CRI is not supported offline, only docker"; exit 1; }
  2465. [[ "$KUBE_CRI" == "containerd" && "${KUBE_CRI_ENDPOINT}" == "/var/run/dockershim.sock" ]] && KUBE_CRI_ENDPOINT="unix:///run/containerd/containerd.sock"
  2466. [[ "$KUBE_CRI" == "cri-o" && "${KUBE_CRI_ENDPOINT}" == "/var/run/dockershim.sock" ]] && KUBE_CRI_ENDPOINT="unix:///var/run/crio/crio.sock"
  2467. kubelet_nodeRegistration="nodeRegistration:
  2468. criSocket: ${KUBE_CRI_ENDPOINT:-/var/run/dockershim.sock}
  2469. kubeletExtraArgs:
  2470. runtime-cgroups: /system.slice/${KUBE_CRI//-/}.service
  2471. pod-infra-container-image: ${KUBE_IMAGE_REPO}/pause:${PAUSE_VERSION:-3.6}
  2472. "
  2473. }
  2474. # 使用帮助
  2475. function help::usage() {
  2476. cat << EOF
  2477. Install kubernetes cluster using kubeadm.
  2478. Usage:
  2479. $(basename "$0") [command]
  2480. Available Commands:
  2481. init 初始化Kubernetes集群
  2482. reset 重置Kubernetes集群
  2483. add 将节点添加到群集
  2484. del 从群集中删除节点
  2485. renew-cert 续订所有可用的证书
  2486. upgrade 升级kubeadm集群
  2487. update 更新脚本文件
  2488. Flag:
  2489. -m,--master master节点(逗号分隔), 默认: ''
  2490. -w,--worker work节点(逗号分隔), 默认: ''
  2491. -u,--user ssh用户, 默认: ${SSH_USER}
  2492. -p,--password ssh密码
  2493. --private-key ssh私钥
  2494. -P,--port ssh端口, 默认: ${SSH_PORT}
  2495. -v,--version kube版本, 默认: ${KUBE_VERSION}
  2496. -n,--network 群集网络, 选择: [flannel,calico,cilium], 默认: ${KUBE_NETWORK}
  2497. -i,--ingress ingress controller, choose: [nginx], 默认: ${KUBE_INGRESS}
  2498. -ui,--ui 群集web ui, use: [rancher]
  2499. -a,--addon 群集附加组件, use: []
  2500. -M,--monitor 群集监控, use: [prometheus]
  2501. -l,--log 群集日志, choose: [elasticsearch]
  2502. --cri cri tools, choose: [docker,containerd,cri-o], 默认: ${KUBE_CRI}
  2503. --cri-version cri version, 默认: ${KUBE_CRI_VERSION}
  2504. --cri-endpoint cri endpoint, 默认: ${KUBE_CRI_ENDPOINT}
  2505. -U,--upgrade-kernel 升级内核
  2506. -of,--offline-file 指定要加载的离线文件
  2507. --10years 证书期限为10年
  2508. --sudo sudo模式
  2509. --sudo-user sudo用户
  2510. --sudo-password sudo用户密码
  2511. Example:
  2512. [init cluster]
  2513. $0 init \\
  2514. --master 192.168.77.130,192.168.77.131,192.168.77.132 \\
  2515. --worker 192.168.77.133,192.168.77.134,192.168.77.135 \\
  2516. --user root \\
  2517. --password 123456 \\
  2518. --version 1.20.4
  2519. [reset cluster]
  2520. $0 reset \\
  2521. --user root \\
  2522. --password 123456
  2523. [add node]
  2524. $0 add \\
  2525. --master 192.168.77.140,192.168.77.141 \\
  2526. --worker 192.168.77.143,192.168.77.144 \\
  2527. --user root \\
  2528. --password 123456 \\
  2529. --version 1.20.4
  2530. [del node]
  2531. $0 del \\
  2532. --master 192.168.77.140,192.168.77.141 \\
  2533. --worker 192.168.77.143,192.168.77.144 \\
  2534. --user root \\
  2535. --password 123456
  2536. [other]
  2537. $0 renew-cert --user root --password 123456
  2538. $0 upgrade --version 1.20.4 --user root --password 123456
  2539. $0 update
  2540. $0 add --ingress traefik
  2541. $0 add --monitor prometheus
  2542. $0 add --log elasticsearch
  2543. $0 add --storage rook
  2544. $0 add --ui dashboard
  2545. $0 add --addon nodelocaldns
  2546. EOF
  2547. exit 1
  2548. }
  2549. ######################################################################################################
  2550. # main
  2551. ######################################################################################################
  2552. [ "$#" == "0" ] && help::usage
  2553. while [ "${1:-}" != "" ]; do
  2554. case $1 in
  2555. init ) INIT_TAG=1
  2556. ;;
  2557. reset ) RESET_TAG=1
  2558. ;;
  2559. add ) ADD_TAG=1
  2560. ;;
  2561. del ) DEL_TAG=1
  2562. ;;
  2563. renew-cert ) RENEW_CERT_TAG=1
  2564. ;;
  2565. upgrade ) UPGRADE_TAG=1
  2566. ;;
  2567. update ) UPDATE_TAG=1
  2568. ;;
  2569. -m | --master ) shift
  2570. MASTER_NODES=${1:-$MASTER_NODES}
  2571. ;;
  2572. -w | --worker ) shift
  2573. WORKER_NODES=${1:-$WORKER_NODES}
  2574. ;;
  2575. -u | --user ) shift
  2576. SSH_USER=${1:-$SSH_USER}
  2577. ;;
  2578. -p | --password ) shift
  2579. SSH_PASSWORD=${1:-$SSH_PASSWORD}
  2580. ;;
  2581. --private-key ) shift
  2582. SSH_PRIVATE_KEY=${1:-$SSH_SSH_PRIVATE_KEY}
  2583. ;;
  2584. -P | --port ) shift
  2585. SSH_PORT=${1:-$SSH_PORT}
  2586. ;;
  2587. -v | --version ) shift
  2588. KUBE_VERSION=${1:-$KUBE_VERSION}
  2589. ;;
  2590. -n | --network ) shift
  2591. NETWORK_TAG=1
  2592. KUBE_NETWORK=${1:-$KUBE_NETWORK}
  2593. ;;
  2594. -i | --ingress ) shift
  2595. INGRESS_TAG=1
  2596. KUBE_INGRESS=${1:-$KUBE_INGRESS}
  2597. ;;
  2598. -M | --monitor ) shift
  2599. MONITOR_TAG=1
  2600. KUBE_MONITOR=${1:-$KUBE_MONITOR}
  2601. ;;
  2602. -l | --log ) shift
  2603. LOG_TAG=1
  2604. KUBE_LOG=${1:-$KUBE_LOG}
  2605. ;;
  2606. -s | --storage ) shift
  2607. STORAGE_TAG=1
  2608. KUBE_STORAGE=${1:-$KUBE_STORAGE}
  2609. ;;
  2610. -ui | --ui ) shift
  2611. UI_TAG=1
  2612. ;;
  2613. -a | --addon ) shift
  2614. ADDON_TAG=1
  2615. ;;
  2616. --cri ) shift
  2617. KUBE_CRI=${1:-$KUBE_CRI}
  2618. ;;
  2619. --cri-version ) shift
  2620. KUBE_CRI_VERSION=${1:-$KUBE_CRI_VERSION}
  2621. ;;
  2622. --cri-endpoint ) shift
  2623. KUBE_CRI_ENDPOINT=${1:-$KUBE_CRI_ENDPOINT}
  2624. ;;
  2625. -U | --upgrade-kernel ) UPGRADE_KERNEL_TAG=1
  2626. ;;
  2627. --mgmt-node-ip ) MGMT_NODE_IP="first_master_ip"
  2628. ;;
  2629. -of | --offline-file ) shift
  2630. OFFLINE_TAG=1
  2631. OFFLINE_FILE=${1:-$OFFLINE_FILE}
  2632. ;;
  2633. --10years ) CERT_YEAR_TAG=1
  2634. ;;
  2635. --sudo ) SUDO_TAG=1
  2636. ;;
  2637. --sudo-user ) shift
  2638. SUDO_USER=${1:-$SUDO_USER}
  2639. ;;
  2640. --sudo-password ) shift
  2641. SUDO_PASSWORD=${1:-}
  2642. ;;
  2643. * ) help::usage
  2644. exit 1
  2645. esac
  2646. shift
  2647. done
  2648. # 开始
  2649. log::info "[start]" "bash $0 ${SCRIPT_PARAMETER//${SSH_PASSWORD:-${SUDO_PASSWORD:-}}/zzzzzz}"
  2650. # 数据处理
  2651. transform::data
  2652. # 预检
  2653. check::preflight
  2654. # 动作
  2655. if [[ "${INIT_TAG:-}" == "1" ]]; then
  2656. [[ "$MASTER_NODES" == "" ]] && MASTER_NODES="127.0.0.1"
  2657. init::cluster
  2658. elif [[ "${ADD_TAG:-}" == "1" ]]; then
  2659. [[ "${NETWORK_TAG:-}" == "1" ]] && { add::network; add=1; }
  2660. [[ "${INGRESS_TAG:-}" == "1" ]] && { add::ingress; add=1; }
  2661. [[ "${STORAGE_TAG:-}" == "1" ]] && { add::storage; add=1; }
  2662. [[ "${MONITOR_TAG:-}" == "1" ]] && { add::monitor; add=1; }
  2663. [[ "${LOG_TAG:-}" == "1" ]] && { add::log; add=1; }
  2664. [[ "${UI_TAG:-}" == "1" ]] && { add::ui; add=1; }
  2665. [[ "${ADDON_TAG:-}" == "1" ]] && { add::addon; add=1; }
  2666. [[ "$MASTER_NODES" != "" || "$WORKER_NODES" != "" ]] && { add::node; add=1; }
  2667. [[ "${add:-}" != "1" ]] && help::usage
  2668. elif [[ "${DEL_TAG:-}" == "1" ]]; then
  2669. if [[ "$MASTER_NODES" != "" || "$WORKER_NODES" != "" ]]; then del::node; else help::usage; fi
  2670. elif [[ "${RESET_TAG:-}" == "1" ]]; then
  2671. reset::cluster
  2672. elif [[ "${RENEW_CERT_TAG:-}" == "1" ]]; then
  2673. cert::renew
  2674. elif [[ "${UPGRADE_TAG:-}" == "1" ]]; then
  2675. upgrade::cluster
  2676. elif [[ "${UPDATE_TAG:-}" == "1" ]]; then
  2677. update::self
  2678. else
  2679. help::usage
  2680. fi
  2681. # bash <(curl -s http://git.yvanui.com/lizhiwei/jztd-deploy/raw/master/sd_dsl/02k8s-install-centos.sh) [cmd]