Skip to content

Commit

Permalink
Merge pull request #646 from Shopify/kubectl_out_encoding
Browse files Browse the repository at this point in the history
Mark kubectl-sourced strings with invalid encoding as UTF-8
  • Loading branch information
KnVerey committed Jan 27, 2020
2 parents d1e52f4 + 11ef6ba commit 8abe30d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## next

*Bug Fixes*
- Help ruby correctly identify kubectl output encoding. [#646](https://github.com/Shopify/krane/pull/646)

## 1.1.1

*Enhancements*
Expand Down
11 changes: 10 additions & 1 deletion lib/krane/kubectl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,16 @@ def run(*args, log_failure: nil, use_context: true, use_namespace: true, output:
(1..attempts).to_a.each do |current_attempt|
logger.debug("Running command (attempt #{current_attempt}): #{cmd.join(' ')}")
out, err, st = Open3.capture3(*cmd)
logger.debug("Kubectl out: " + out.gsub(/\s+/, ' ')) unless output_is_sensitive

# https://github.com/Shopify/krane/issues/395
unless out.valid_encoding?
out = out.dup.force_encoding(Encoding::UTF_8)
end

if logger.debug? && !output_is_sensitive
# don't do the gsub unless we're going to print this
logger.debug("Kubectl out: " + out.gsub(/\s+/, ' '))
end

break if st.success?
raise(ResourceNotFoundError, err) if err.match(ERROR_MATCHERS[:not_found]) && raise_if_not_found
Expand Down
23 changes: 23 additions & 0 deletions test/unit/krane/kubectl_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,29 @@ def test_retry_delay_backoff
end
end

def test_kubectl_run_fixes_encoding_when_locales_set_to_non_utf8
ext_before = Encoding.default_external
int_before = Encoding.default_internal
logger.level = ::Logger::DEBUG
utf8 = "こんにちは!hélas!"

# This is how setting the env from https://github.com/Shopify/krane/issues/395 manifests internally
Encoding.default_external = Encoding::US_ASCII
Encoding.default_internal = nil

# put the string through the default external encoder
data = %x(echo #{utf8})
assert_equal(Encoding::US_ASCII, data.encoding)

stub_open3(%W(kubectl get pods --namespace=testn --context=testc --request-timeout=#{timeout}), resp: data)
out, _err, _st = build_kubectl.run("get", "pods")
assert_equal(utf8, out)
assert_equal(Encoding::UTF_8, out.encoding)
ensure
Encoding.default_external = ext_before
Encoding.default_internal = int_before
end

private

def timeout
Expand Down

0 comments on commit 8abe30d

Please sign in to comment.