Skip to content

Commit

Permalink
Update kubectl version parsing
Browse files Browse the repository at this point in the history
Signed-off-by: Akash Manohar <[email protected]>
  • Loading branch information
HashNuke committed Aug 30, 2023
1 parent c267805 commit 163e913
Showing 1 changed file with 36 additions and 15 deletions.
51 changes: 36 additions & 15 deletions src/utils/system_information.cr
Original file line number Diff line number Diff line change
Expand Up @@ -107,26 +107,47 @@ end
# version # => "1.12"
# ```
#
# For reference, below are example client and server version strings from "kubectl version" output
#
# ```
# Client Version: version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.0", GitCommit:"cb303e613a121a29364f75cc67d3d580833a7479", GitTreeState:"clean", BuildDate:"2021-04-08T16:31:21Z", GoVersion:"go1.16.1", Compiler:"gc", Platform:"linux/amd64"}
# Server Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.2", GitCommit:"faecb196815e248d3ecfb03c680a4507229c2a56", GitTreeState:"clean", BuildDate:"2021-01-21T01:11:42Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}
# ```
#
# TODO Function could be updated to rely on the JSON output of "kubectl version -o json" instead of regex parsing
#
# Returns the version as a string (Example: 1.12, 1.20, etc)
def kubectl_version(kubectl_response, version_for = "client", verbose = false)
# version_for can be "client" or "server"
resp = kubectl_response.match /#{version_for.capitalize} Version: version.Info{(Major:"(([0-9]{1,3})"\, )Minor:"([0-9]{1,3}[+]?)")/
Log.for("verbose").info { resp } if verbose
version_info_json = kubectl_response

# Strip the server connection warning if it exists in the output.
if kubectl_response.includes?("The connection to the server")
version_info_lines = version_info_json.split("\n")
version_info_json = version_info_lines[0, version_info_lines.size - 1].join("\n")
end

if resp
"#{resp && resp.not_nil![3]}.#{resp && resp.not_nil![4]}"
# Look for the appropriate key depending on client or server version lookup
version_key = "clientVersion"
if version_for == "server"
version_key = "serverVersion"
end

# Attempt to parse version output
# Or return blank string if json parse exception
begin
version_data = JSON.parse(version_info_json)
rescue ex : JSON::ParseException
return ""
end

# If the specific server/client version info does not exist,
# then return blank string
if version_data.as_h.has_key?(version_key)
version_info = version_data[version_key]
else
""
return ""
end

# If major and minor keys do not exist, then return blank string
if version_info.as_h.has_key?("major") && version_info.as_h.has_key?("minor")
major_version = version_info["major"].as_s
minor_version = version_info["minor"].as_s
else
return ""
end

"#{major_version}.#{minor_version}"
end

# Check if client version is not too many versions behind server version
Expand Down

0 comments on commit 163e913

Please sign in to comment.