Update kubernetes to v1.13.0

Signed-off-by: Lantao Liu <lantaol@google.com>
This commit is contained in:
Lantao Liu 2018-12-17 11:54:21 -08:00
parent afb12d728c
commit 2baa96e0e2
101 changed files with 6482 additions and 5388 deletions

View File

@ -21,11 +21,9 @@ github.com/docker/go-metrics 4ea375f7759c82740c893fc030bc37088d2ec098
github.com/docker/go-units v0.3.1 github.com/docker/go-units v0.3.1
github.com/docker/spdystream 449fdfce4d962303d702fec724ef0ad181c92528 github.com/docker/spdystream 449fdfce4d962303d702fec724ef0ad181c92528
github.com/emicklei/go-restful v2.2.1 github.com/emicklei/go-restful v2.2.1
github.com/ghodss/yaml v1.0.0
github.com/godbus/dbus v3 github.com/godbus/dbus v3
github.com/gogo/googleapis 08a7655d27152912db7aaf4f983275eaf8d128ef github.com/gogo/googleapis 08a7655d27152912db7aaf4f983275eaf8d128ef
github.com/gogo/protobuf v1.0.0 github.com/gogo/protobuf v1.0.0
github.com/golang/glog 44145f04b68cf362d9c4df2182967c2275eaefed
github.com/golang/protobuf v1.1.0 github.com/golang/protobuf v1.1.0
github.com/google/gofuzz 44d81051d367757e1c7c6a5a86423ece9afcf63c github.com/google/gofuzz 44d81051d367757e1c7c6a5a86423ece9afcf63c
github.com/grpc-ecosystem/go-grpc-prometheus v1.1 github.com/grpc-ecosystem/go-grpc-prometheus v1.1
@ -69,10 +67,12 @@ golang.org/x/time f51c12702a4d776e4c1fa9b0fabab841babae631
google.golang.org/genproto d80a6e20e776b0b17a324d0ba1ab50a39c8e8944 google.golang.org/genproto d80a6e20e776b0b17a324d0ba1ab50a39c8e8944
google.golang.org/grpc v1.12.0 google.golang.org/grpc v1.12.0
gopkg.in/inf.v0 3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4 gopkg.in/inf.v0 3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4
gopkg.in/yaml.v2 53feefa2559fb8dfa8d81baad31be332c97d6c77 gopkg.in/yaml.v2 v2.2.1
k8s.io/api kubernetes-1.12.0 k8s.io/api kubernetes-1.13.0
k8s.io/apimachinery kubernetes-1.12.0 k8s.io/apimachinery kubernetes-1.13.0
k8s.io/apiserver kubernetes-1.12.0 k8s.io/apiserver kubernetes-1.13.0
k8s.io/client-go kubernetes-1.12.0 k8s.io/client-go kubernetes-1.13.0
k8s.io/kubernetes v1.12.0 k8s.io/klog 8139d8cb77af419532b33dfa7dd09fbc5f1d344f
k8s.io/utils cd34563cd63c2bd7c6fe88a73c4dcf34ed8a67cb k8s.io/kubernetes v1.13.0
k8s.io/utils 0d26856f57b32ec3398579285e5c8a2bfe8c5243
sigs.k8s.io/yaml v1.1.0

325
vendor/gopkg.in/yaml.v2/LICENSE generated vendored
View File

@ -1,188 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2011-2014 - Canonical Inc. TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
This software is licensed under the LGPLv3, included below. 1. Definitions.
As a special exception to the GNU Lesser General Public License version 3 "License" shall mean the terms and conditions for use, reproduction,
("LGPL3"), the copyright holders of this Library give you permission to and distribution as defined by Sections 1 through 9 of this document.
convey to a third party a Combined Work that links statically or dynamically
to this Library without providing any Minimal Corresponding Source or
Minimal Application Code as set out in 4d or providing the installation
information set out in section 4e, provided that you comply with the other
provisions of LGPL3 and provided that you meet, for the Application the
terms and conditions of the license(s) which apply to the Application.
Except as stated in this special exception, the provisions of LGPL3 will "Licensor" shall mean the copyright owner or entity authorized by
continue to comply in full to this Library. If you modify this Library, you the copyright owner that is granting the License.
may apply this exception to your version of this Library, but you are not
obliged to do so. If you do not wish to do so, delete this exception
statement from your version. This exception does not (and cannot) modify any
license terms which apply to the Application, with which you must still
comply.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
GNU LESSER GENERAL PUBLIC LICENSE "You" (or "Your") shall mean an individual or Legal Entity
Version 3, 29 June 2007 exercising permissions granted by this License.
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> "Source" form shall mean the preferred form for making modifications,
Everyone is permitted to copy and distribute verbatim copies including but not limited to software source code, documentation
of this license document, but changing it is not allowed. source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
This version of the GNU Lesser General Public License incorporates "Work" shall mean the work of authorship, whether in Source or
the terms and conditions of version 3 of the GNU General Public Object form, made available under the License, as indicated by a
License, supplemented by the additional permissions listed below. copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
0. Additional Definitions. "Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
As used herein, "this License" refers to version 3 of the GNU Lesser "Contribution" shall mean any work of authorship, including
General Public License, and the "GNU GPL" refers to version 3 of the GNU the original version of the Work and any modifications or additions
General Public License. to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"The Library" refers to a covered work governed by this License, "Contributor" shall mean Licensor and any individual or Legal Entity
other than an Application or a Combined Work as defined below. on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
An "Application" is any work that makes use of an interface provided 2. Grant of Copyright License. Subject to the terms and conditions of
by the Library, but which is not otherwise based on the Library. this License, each Contributor hereby grants to You a perpetual,
Defining a subclass of a class defined by the Library is deemed a mode worldwide, non-exclusive, no-charge, royalty-free, irrevocable
of using an interface provided by the Library. copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
A "Combined Work" is a work produced by combining or linking an 3. Grant of Patent License. Subject to the terms and conditions of
Application with the Library. The particular version of the Library this License, each Contributor hereby grants to You a perpetual,
with which the Combined Work was made is also called the "Linked worldwide, non-exclusive, no-charge, royalty-free, irrevocable
Version". (except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
The "Minimal Corresponding Source" for a Combined Work means the 4. Redistribution. You may reproduce and distribute copies of the
Corresponding Source for the Combined Work, excluding any source code Work or Derivative Works thereof in any medium, with or without
for portions of the Combined Work that, considered in isolation, are modifications, and in Source or Object form, provided that You
based on the Application, and not on the Linked Version. meet the following conditions:
The "Corresponding Application Code" for a Combined Work means the (a) You must give any other recipients of the Work or
object code and/or source code for the Application, including any data Derivative Works a copy of this License; and
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL. (b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
You may convey a covered work under sections 3 and 4 of this License (c) You must retain, in the Source form of any Derivative Works
without being bound by section 3 of the GNU GPL. that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
2. Conveying Modified Versions. (d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
If you modify a copy of the Library, and, in your modifications, a You may add Your own copyright statement to Your modifications and
facility refers to a function or data to be supplied by an Application may provide additional or different license terms and conditions
that uses the facility (other than as an argument passed when the for use, reproduction, or distribution of Your modifications, or
facility is invoked), then you may convey a copy of the modified for any such Derivative Works as a whole, provided Your use,
version: reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
a) under this License, provided that you make a good faith effort to 5. Submission of Contributions. Unless You explicitly state otherwise,
ensure that, in the event an Application does not supply the any Contribution intentionally submitted for inclusion in the Work
function or data, the facility still operates, and performs by You to the Licensor shall be under the terms and conditions of
whatever part of its purpose remains meaningful, or this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
b) under the GNU GPL, with none of the additional permissions of 6. Trademarks. This License does not grant permission to use the trade
this License applicable to that copy. names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
3. Object Code Incorporating Material from Library Header Files. 7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
The object code form of an Application may incorporate material from 8. Limitation of Liability. In no event and under no legal theory,
a header file that is part of the Library. You may convey such object whether in tort (including negligence), contract, or otherwise,
code under terms of your choice, provided that, if the incorporated unless required by applicable law (such as deliberate and grossly
material is not limited to numerical parameters, data structure negligent acts) or agreed to in writing, shall any Contributor be
layouts and accessors, or small macros, inline functions and templates liable to You for damages, including any direct, indirect, special,
(ten or fewer lines in length), you do both of the following: incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
a) Give prominent notice with each copy of the object code that the 9. Accepting Warranty or Additional Liability. While redistributing
Library is used in it and that the Library and its use are the Work or Derivative Works thereof, You may choose to offer,
covered by this License. and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
b) Accompany the object code with a copy of the GNU GPL and this license END OF TERMS AND CONDITIONS
document.
4. Combined Works. APPENDIX: How to apply the Apache License to your work.
You may convey a Combined Work under terms of your choice that, To apply the Apache License to your work, attach the following
taken together, effectively do not restrict modification of the boilerplate notice, with the fields enclosed by brackets "{}"
portions of the Library contained in the Combined Work and reverse replaced with your own identifying information. (Don't include
engineering for debugging such modifications, if you also do each of the brackets!) The text should be enclosed in the appropriate
the following: comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
a) Give prominent notice with each copy of the Combined Work that Copyright {yyyy} {name of copyright owner}
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license Licensed under the Apache License, Version 2.0 (the "License");
document. you may not use this file except in compliance with the License.
You may obtain a copy of the License at
c) For a Combined Work that displays copyright notices during http://www.apache.org/licenses/LICENSE-2.0
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following: Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
0) Convey the Minimal Corresponding Source under the terms of this WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
License, and the Corresponding Application Code in a form See the License for the specific language governing permissions and
suitable for, and under terms that permit, the user to limitations under the License.
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

13
vendor/gopkg.in/yaml.v2/NOTICE generated vendored Normal file
View File

@ -0,0 +1,13 @@
Copyright 2011-2016 Canonical Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

4
vendor/gopkg.in/yaml.v2/README.md generated vendored
View File

@ -42,7 +42,7 @@ The package API for yaml v2 will remain stable as described in [gopkg.in](https:
License License
------- -------
The yaml package is licensed under the LGPL with an exception that allows it to be linked statically. Please see the LICENSE file for details. The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details.
Example Example
@ -65,6 +65,8 @@ b:
d: [3, 4] d: [3, 4]
` `
// Note: struct fields must be public in order for unmarshal to
// correctly populate the data.
type T struct { type T struct {
A string A string
B struct { B struct {

55
vendor/gopkg.in/yaml.v2/apic.go generated vendored
View File

@ -2,7 +2,6 @@ package yaml
import ( import (
"io" "io"
"os"
) )
func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) {
@ -48,9 +47,9 @@ func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err
return n, nil return n, nil
} }
// File read handler. // Reader read handler.
func yaml_file_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) {
return parser.input_file.Read(buffer) return parser.input_reader.Read(buffer)
} }
// Set a string input. // Set a string input.
@ -64,12 +63,12 @@ func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) {
} }
// Set a file input. // Set a file input.
func yaml_parser_set_input_file(parser *yaml_parser_t, file *os.File) { func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) {
if parser.read_handler != nil { if parser.read_handler != nil {
panic("must set the input source only once") panic("must set the input source only once")
} }
parser.read_handler = yaml_file_read_handler parser.read_handler = yaml_reader_read_handler
parser.input_file = file parser.input_reader = r
} }
// Set the source encoding. // Set the source encoding.
@ -81,14 +80,13 @@ func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) {
} }
// Create a new emitter object. // Create a new emitter object.
func yaml_emitter_initialize(emitter *yaml_emitter_t) bool { func yaml_emitter_initialize(emitter *yaml_emitter_t) {
*emitter = yaml_emitter_t{ *emitter = yaml_emitter_t{
buffer: make([]byte, output_buffer_size), buffer: make([]byte, output_buffer_size),
raw_buffer: make([]byte, 0, output_raw_buffer_size), raw_buffer: make([]byte, 0, output_raw_buffer_size),
states: make([]yaml_emitter_state_t, 0, initial_stack_size), states: make([]yaml_emitter_state_t, 0, initial_stack_size),
events: make([]yaml_event_t, 0, initial_queue_size), events: make([]yaml_event_t, 0, initial_queue_size),
} }
return true
} }
// Destroy an emitter object. // Destroy an emitter object.
@ -102,9 +100,10 @@ func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error {
return nil return nil
} }
// File write handler. // yaml_writer_write_handler uses emitter.output_writer to write the
func yaml_file_write_handler(emitter *yaml_emitter_t, buffer []byte) error { // emitted text.
_, err := emitter.output_file.Write(buffer) func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error {
_, err := emitter.output_writer.Write(buffer)
return err return err
} }
@ -118,12 +117,12 @@ func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]by
} }
// Set a file output. // Set a file output.
func yaml_emitter_set_output_file(emitter *yaml_emitter_t, file io.Writer) { func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) {
if emitter.write_handler != nil { if emitter.write_handler != nil {
panic("must set the output target only once") panic("must set the output target only once")
} }
emitter.write_handler = yaml_file_write_handler emitter.write_handler = yaml_writer_write_handler
emitter.output_file = file emitter.output_writer = w
} }
// Set the output encoding. // Set the output encoding.
@ -252,41 +251,41 @@ func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) {
// //
// Create STREAM-START. // Create STREAM-START.
func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) bool { func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) {
*event = yaml_event_t{ *event = yaml_event_t{
typ: yaml_STREAM_START_EVENT, typ: yaml_STREAM_START_EVENT,
encoding: encoding, encoding: encoding,
} }
return true
} }
// Create STREAM-END. // Create STREAM-END.
func yaml_stream_end_event_initialize(event *yaml_event_t) bool { func yaml_stream_end_event_initialize(event *yaml_event_t) {
*event = yaml_event_t{ *event = yaml_event_t{
typ: yaml_STREAM_END_EVENT, typ: yaml_STREAM_END_EVENT,
} }
return true
} }
// Create DOCUMENT-START. // Create DOCUMENT-START.
func yaml_document_start_event_initialize(event *yaml_event_t, version_directive *yaml_version_directive_t, func yaml_document_start_event_initialize(
tag_directives []yaml_tag_directive_t, implicit bool) bool { event *yaml_event_t,
version_directive *yaml_version_directive_t,
tag_directives []yaml_tag_directive_t,
implicit bool,
) {
*event = yaml_event_t{ *event = yaml_event_t{
typ: yaml_DOCUMENT_START_EVENT, typ: yaml_DOCUMENT_START_EVENT,
version_directive: version_directive, version_directive: version_directive,
tag_directives: tag_directives, tag_directives: tag_directives,
implicit: implicit, implicit: implicit,
} }
return true
} }
// Create DOCUMENT-END. // Create DOCUMENT-END.
func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) bool { func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) {
*event = yaml_event_t{ *event = yaml_event_t{
typ: yaml_DOCUMENT_END_EVENT, typ: yaml_DOCUMENT_END_EVENT,
implicit: implicit, implicit: implicit,
} }
return true
} }
///* ///*
@ -348,7 +347,7 @@ func yaml_sequence_end_event_initialize(event *yaml_event_t) bool {
} }
// Create MAPPING-START. // Create MAPPING-START.
func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) bool { func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) {
*event = yaml_event_t{ *event = yaml_event_t{
typ: yaml_MAPPING_START_EVENT, typ: yaml_MAPPING_START_EVENT,
anchor: anchor, anchor: anchor,
@ -356,15 +355,13 @@ func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte
implicit: implicit, implicit: implicit,
style: yaml_style_t(style), style: yaml_style_t(style),
} }
return true
} }
// Create MAPPING-END. // Create MAPPING-END.
func yaml_mapping_end_event_initialize(event *yaml_event_t) bool { func yaml_mapping_end_event_initialize(event *yaml_event_t) {
*event = yaml_event_t{ *event = yaml_event_t{
typ: yaml_MAPPING_END_EVENT, typ: yaml_MAPPING_END_EVENT,
} }
return true
} }
// Destroy an event object. // Destroy an event object.
@ -471,7 +468,7 @@ func yaml_event_delete(event *yaml_event_t) {
// } context // } context
// tag_directive *yaml_tag_directive_t // tag_directive *yaml_tag_directive_t
// //
// context.error = YAML_NO_ERROR // Eliminate a compliler warning. // context.error = YAML_NO_ERROR // Eliminate a compiler warning.
// //
// assert(document) // Non-NULL document object is expected. // assert(document) // Non-NULL document object is expected.
// //

226
vendor/gopkg.in/yaml.v2/decode.go generated vendored
View File

@ -4,6 +4,7 @@ import (
"encoding" "encoding"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io"
"math" "math"
"reflect" "reflect"
"strconv" "strconv"
@ -22,6 +23,8 @@ type node struct {
kind int kind int
line, column int line, column int
tag string tag string
// For an alias node, alias holds the resolved alias.
alias *node
value string value string
implicit bool implicit bool
children []*node children []*node
@ -35,6 +38,7 @@ type parser struct {
parser yaml_parser_t parser yaml_parser_t
event yaml_event_t event yaml_event_t
doc *node doc *node
doneInit bool
} }
func newParser(b []byte) *parser { func newParser(b []byte) *parser {
@ -42,21 +46,30 @@ func newParser(b []byte) *parser {
if !yaml_parser_initialize(&p.parser) { if !yaml_parser_initialize(&p.parser) {
panic("failed to initialize YAML emitter") panic("failed to initialize YAML emitter")
} }
if len(b) == 0 { if len(b) == 0 {
b = []byte{'\n'} b = []byte{'\n'}
} }
yaml_parser_set_input_string(&p.parser, b) yaml_parser_set_input_string(&p.parser, b)
p.skip()
if p.event.typ != yaml_STREAM_START_EVENT {
panic("expected stream start event, got " + strconv.Itoa(int(p.event.typ)))
}
p.skip()
return &p return &p
} }
func newParserFromReader(r io.Reader) *parser {
p := parser{}
if !yaml_parser_initialize(&p.parser) {
panic("failed to initialize YAML emitter")
}
yaml_parser_set_input_reader(&p.parser, r)
return &p
}
func (p *parser) init() {
if p.doneInit {
return
}
p.expect(yaml_STREAM_START_EVENT)
p.doneInit = true
}
func (p *parser) destroy() { func (p *parser) destroy() {
if p.event.typ != yaml_NO_EVENT { if p.event.typ != yaml_NO_EVENT {
yaml_event_delete(&p.event) yaml_event_delete(&p.event)
@ -64,16 +77,35 @@ func (p *parser) destroy() {
yaml_parser_delete(&p.parser) yaml_parser_delete(&p.parser)
} }
func (p *parser) skip() { // expect consumes an event from the event stream and
if p.event.typ != yaml_NO_EVENT { // checks that it's of the expected type.
func (p *parser) expect(e yaml_event_type_t) {
if p.event.typ == yaml_NO_EVENT {
if !yaml_parser_parse(&p.parser, &p.event) {
p.fail()
}
}
if p.event.typ == yaml_STREAM_END_EVENT { if p.event.typ == yaml_STREAM_END_EVENT {
failf("attempted to go past the end of stream; corrupted value?") failf("attempted to go past the end of stream; corrupted value?")
} }
if p.event.typ != e {
p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ)
p.fail()
}
yaml_event_delete(&p.event) yaml_event_delete(&p.event)
p.event.typ = yaml_NO_EVENT
}
// peek peeks at the next event in the event stream,
// puts the results into p.event and returns the event type.
func (p *parser) peek() yaml_event_type_t {
if p.event.typ != yaml_NO_EVENT {
return p.event.typ
} }
if !yaml_parser_parse(&p.parser, &p.event) { if !yaml_parser_parse(&p.parser, &p.event) {
p.fail() p.fail()
} }
return p.event.typ
} }
func (p *parser) fail() { func (p *parser) fail() {
@ -81,6 +113,10 @@ func (p *parser) fail() {
var line int var line int
if p.parser.problem_mark.line != 0 { if p.parser.problem_mark.line != 0 {
line = p.parser.problem_mark.line line = p.parser.problem_mark.line
// Scanner errors don't iterate line before returning error
if p.parser.error == yaml_SCANNER_ERROR {
line++
}
} else if p.parser.context_mark.line != 0 { } else if p.parser.context_mark.line != 0 {
line = p.parser.context_mark.line line = p.parser.context_mark.line
} }
@ -103,7 +139,8 @@ func (p *parser) anchor(n *node, anchor []byte) {
} }
func (p *parser) parse() *node { func (p *parser) parse() *node {
switch p.event.typ { p.init()
switch p.peek() {
case yaml_SCALAR_EVENT: case yaml_SCALAR_EVENT:
return p.scalar() return p.scalar()
case yaml_ALIAS_EVENT: case yaml_ALIAS_EVENT:
@ -118,9 +155,8 @@ func (p *parser) parse() *node {
// Happens when attempting to decode an empty buffer. // Happens when attempting to decode an empty buffer.
return nil return nil
default: default:
panic("attempted to parse unknown event: " + strconv.Itoa(int(p.event.typ))) panic("attempted to parse unknown event: " + p.event.typ.String())
} }
panic("unreachable")
} }
func (p *parser) node(kind int) *node { func (p *parser) node(kind int) *node {
@ -135,19 +171,20 @@ func (p *parser) document() *node {
n := p.node(documentNode) n := p.node(documentNode)
n.anchors = make(map[string]*node) n.anchors = make(map[string]*node)
p.doc = n p.doc = n
p.skip() p.expect(yaml_DOCUMENT_START_EVENT)
n.children = append(n.children, p.parse()) n.children = append(n.children, p.parse())
if p.event.typ != yaml_DOCUMENT_END_EVENT { p.expect(yaml_DOCUMENT_END_EVENT)
panic("expected end of document event but got " + strconv.Itoa(int(p.event.typ)))
}
p.skip()
return n return n
} }
func (p *parser) alias() *node { func (p *parser) alias() *node {
n := p.node(aliasNode) n := p.node(aliasNode)
n.value = string(p.event.anchor) n.value = string(p.event.anchor)
p.skip() n.alias = p.doc.anchors[n.value]
if n.alias == nil {
failf("unknown anchor '%s' referenced", n.value)
}
p.expect(yaml_ALIAS_EVENT)
return n return n
} }
@ -157,29 +194,29 @@ func (p *parser) scalar() *node {
n.tag = string(p.event.tag) n.tag = string(p.event.tag)
n.implicit = p.event.implicit n.implicit = p.event.implicit
p.anchor(n, p.event.anchor) p.anchor(n, p.event.anchor)
p.skip() p.expect(yaml_SCALAR_EVENT)
return n return n
} }
func (p *parser) sequence() *node { func (p *parser) sequence() *node {
n := p.node(sequenceNode) n := p.node(sequenceNode)
p.anchor(n, p.event.anchor) p.anchor(n, p.event.anchor)
p.skip() p.expect(yaml_SEQUENCE_START_EVENT)
for p.event.typ != yaml_SEQUENCE_END_EVENT { for p.peek() != yaml_SEQUENCE_END_EVENT {
n.children = append(n.children, p.parse()) n.children = append(n.children, p.parse())
} }
p.skip() p.expect(yaml_SEQUENCE_END_EVENT)
return n return n
} }
func (p *parser) mapping() *node { func (p *parser) mapping() *node {
n := p.node(mappingNode) n := p.node(mappingNode)
p.anchor(n, p.event.anchor) p.anchor(n, p.event.anchor)
p.skip() p.expect(yaml_MAPPING_START_EVENT)
for p.event.typ != yaml_MAPPING_END_EVENT { for p.peek() != yaml_MAPPING_END_EVENT {
n.children = append(n.children, p.parse(), p.parse()) n.children = append(n.children, p.parse(), p.parse())
} }
p.skip() p.expect(yaml_MAPPING_END_EVENT)
return n return n
} }
@ -188,9 +225,10 @@ func (p *parser) mapping() *node {
type decoder struct { type decoder struct {
doc *node doc *node
aliases map[string]bool aliases map[*node]bool
mapType reflect.Type mapType reflect.Type
terrors []string terrors []string
strict bool
} }
var ( var (
@ -198,11 +236,13 @@ var (
durationType = reflect.TypeOf(time.Duration(0)) durationType = reflect.TypeOf(time.Duration(0))
defaultMapType = reflect.TypeOf(map[interface{}]interface{}{}) defaultMapType = reflect.TypeOf(map[interface{}]interface{}{})
ifaceType = defaultMapType.Elem() ifaceType = defaultMapType.Elem()
timeType = reflect.TypeOf(time.Time{})
ptrTimeType = reflect.TypeOf(&time.Time{})
) )
func newDecoder() *decoder { func newDecoder(strict bool) *decoder {
d := &decoder{mapType: defaultMapType} d := &decoder{mapType: defaultMapType, strict: strict}
d.aliases = make(map[string]bool) d.aliases = make(map[*node]bool)
return d return d
} }
@ -251,7 +291,7 @@ func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) {
// //
// If n holds a null value, prepare returns before doing anything. // If n holds a null value, prepare returns before doing anything.
func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) {
if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "") { if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "~" || n.value == "" && n.implicit) {
return out, false, false return out, false, false
} }
again := true again := true
@ -308,16 +348,13 @@ func (d *decoder) document(n *node, out reflect.Value) (good bool) {
} }
func (d *decoder) alias(n *node, out reflect.Value) (good bool) { func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
an, ok := d.doc.anchors[n.value] if d.aliases[n] {
if !ok { // TODO this could actually be allowed in some circumstances.
failf("unknown anchor '%s' referenced", n.value)
}
if d.aliases[n.value] {
failf("anchor '%s' value contains itself", n.value) failf("anchor '%s' value contains itself", n.value)
} }
d.aliases[n.value] = true d.aliases[n] = true
good = d.unmarshal(an, out) good = d.unmarshal(n.alias, out)
delete(d.aliases, n.value) delete(d.aliases, n)
return good return good
} }
@ -329,7 +366,7 @@ func resetMap(out reflect.Value) {
} }
} }
func (d *decoder) scalar(n *node, out reflect.Value) (good bool) { func (d *decoder) scalar(n *node, out reflect.Value) bool {
var tag string var tag string
var resolved interface{} var resolved interface{}
if n.tag == "" && !n.implicit { if n.tag == "" && !n.implicit {
@ -353,9 +390,26 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
} }
return true return true
} }
if s, ok := resolved.(string); ok && out.CanAddr() { if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
if u, ok := out.Addr().Interface().(encoding.TextUnmarshaler); ok { // We've resolved to exactly the type we want, so use that.
err := u.UnmarshalText([]byte(s)) out.Set(resolvedv)
return true
}
// Perhaps we can use the value as a TextUnmarshaler to
// set its value.
if out.CanAddr() {
u, ok := out.Addr().Interface().(encoding.TextUnmarshaler)
if ok {
var text []byte
if tag == yaml_BINARY_TAG {
text = []byte(resolved.(string))
} else {
// We let any value be unmarshaled into TextUnmarshaler.
// That might be more lax than we'd like, but the
// TextUnmarshaler itself should bowl out any dubious values.
text = []byte(n.value)
}
err := u.UnmarshalText(text)
if err != nil { if err != nil {
fail(err) fail(err)
} }
@ -366,46 +420,54 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
case reflect.String: case reflect.String:
if tag == yaml_BINARY_TAG { if tag == yaml_BINARY_TAG {
out.SetString(resolved.(string)) out.SetString(resolved.(string))
good = true return true
} else if resolved != nil { }
if resolved != nil {
out.SetString(n.value) out.SetString(n.value)
good = true return true
} }
case reflect.Interface: case reflect.Interface:
if resolved == nil { if resolved == nil {
out.Set(reflect.Zero(out.Type())) out.Set(reflect.Zero(out.Type()))
} else if tag == yaml_TIMESTAMP_TAG {
// It looks like a timestamp but for backward compatibility
// reasons we set it as a string, so that code that unmarshals
// timestamp-like values into interface{} will continue to
// see a string and not a time.Time.
// TODO(v3) Drop this.
out.Set(reflect.ValueOf(n.value))
} else { } else {
out.Set(reflect.ValueOf(resolved)) out.Set(reflect.ValueOf(resolved))
} }
good = true return true
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
switch resolved := resolved.(type) { switch resolved := resolved.(type) {
case int: case int:
if !out.OverflowInt(int64(resolved)) { if !out.OverflowInt(int64(resolved)) {
out.SetInt(int64(resolved)) out.SetInt(int64(resolved))
good = true return true
} }
case int64: case int64:
if !out.OverflowInt(resolved) { if !out.OverflowInt(resolved) {
out.SetInt(resolved) out.SetInt(resolved)
good = true return true
} }
case uint64: case uint64:
if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
out.SetInt(int64(resolved)) out.SetInt(int64(resolved))
good = true return true
} }
case float64: case float64:
if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
out.SetInt(int64(resolved)) out.SetInt(int64(resolved))
good = true return true
} }
case string: case string:
if out.Type() == durationType { if out.Type() == durationType {
d, err := time.ParseDuration(resolved) d, err := time.ParseDuration(resolved)
if err == nil { if err == nil {
out.SetInt(int64(d)) out.SetInt(int64(d))
good = true return true
} }
} }
} }
@ -414,44 +476,49 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
case int: case int:
if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved)) out.SetUint(uint64(resolved))
good = true return true
} }
case int64: case int64:
if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved)) out.SetUint(uint64(resolved))
good = true return true
} }
case uint64: case uint64:
if !out.OverflowUint(uint64(resolved)) { if !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved)) out.SetUint(uint64(resolved))
good = true return true
} }
case float64: case float64:
if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) {
out.SetUint(uint64(resolved)) out.SetUint(uint64(resolved))
good = true return true
} }
} }
case reflect.Bool: case reflect.Bool:
switch resolved := resolved.(type) { switch resolved := resolved.(type) {
case bool: case bool:
out.SetBool(resolved) out.SetBool(resolved)
good = true return true
} }
case reflect.Float32, reflect.Float64: case reflect.Float32, reflect.Float64:
switch resolved := resolved.(type) { switch resolved := resolved.(type) {
case int: case int:
out.SetFloat(float64(resolved)) out.SetFloat(float64(resolved))
good = true return true
case int64: case int64:
out.SetFloat(float64(resolved)) out.SetFloat(float64(resolved))
good = true return true
case uint64: case uint64:
out.SetFloat(float64(resolved)) out.SetFloat(float64(resolved))
good = true return true
case float64: case float64:
out.SetFloat(resolved) out.SetFloat(resolved)
good = true return true
}
case reflect.Struct:
if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
out.Set(resolvedv)
return true
} }
case reflect.Ptr: case reflect.Ptr:
if out.Type().Elem() == reflect.TypeOf(resolved) { if out.Type().Elem() == reflect.TypeOf(resolved) {
@ -459,13 +526,11 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
elem := reflect.New(out.Type().Elem()) elem := reflect.New(out.Type().Elem())
elem.Elem().Set(reflect.ValueOf(resolved)) elem.Elem().Set(reflect.ValueOf(resolved))
out.Set(elem) out.Set(elem)
good = true return true
} }
} }
if !good {
d.terror(n, tag, out) d.terror(n, tag, out)
} return false
return good
} }
func settableValueOf(i interface{}) reflect.Value { func settableValueOf(i interface{}) reflect.Value {
@ -482,6 +547,10 @@ func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
switch out.Kind() { switch out.Kind() {
case reflect.Slice: case reflect.Slice:
out.Set(reflect.MakeSlice(out.Type(), l, l)) out.Set(reflect.MakeSlice(out.Type(), l, l))
case reflect.Array:
if l != out.Len() {
failf("invalid array: want %d elements but got %d", out.Len(), l)
}
case reflect.Interface: case reflect.Interface:
// No type hints. Will have to use a generic sequence. // No type hints. Will have to use a generic sequence.
iface = out iface = out
@ -500,7 +569,9 @@ func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
j++ j++
} }
} }
if out.Kind() != reflect.Array {
out.Set(out.Slice(0, j)) out.Set(out.Slice(0, j))
}
if iface.IsValid() { if iface.IsValid() {
iface.Set(out) iface.Set(out)
} }
@ -561,7 +632,7 @@ func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
} }
e := reflect.New(et).Elem() e := reflect.New(et).Elem()
if d.unmarshal(n.children[i+1], e) { if d.unmarshal(n.children[i+1], e) {
out.SetMapIndex(k, e) d.setMapIndex(n.children[i+1], out, k, e)
} }
} }
} }
@ -569,6 +640,14 @@ func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
return true return true
} }
func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) {
if d.strict && out.MapIndex(k) != zeroValue {
d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface()))
return
}
out.SetMapIndex(k, v)
}
func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) {
outt := out.Type() outt := out.Type()
if outt.Elem() != mapItemType { if outt.Elem() != mapItemType {
@ -616,6 +695,10 @@ func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
elemType = inlineMap.Type().Elem() elemType = inlineMap.Type().Elem()
} }
var doneFields []bool
if d.strict {
doneFields = make([]bool, len(sinfo.FieldsList))
}
for i := 0; i < l; i += 2 { for i := 0; i < l; i += 2 {
ni := n.children[i] ni := n.children[i]
if isMerge(ni) { if isMerge(ni) {
@ -626,6 +709,13 @@ func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
continue continue
} }
if info, ok := sinfo.FieldsMap[name.String()]; ok { if info, ok := sinfo.FieldsMap[name.String()]; ok {
if d.strict {
if doneFields[info.Id] {
d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type()))
continue
}
doneFields[info.Id] = true
}
var field reflect.Value var field reflect.Value
if info.Inline == nil { if info.Inline == nil {
field = out.Field(info.Num) field = out.Field(info.Num)
@ -639,7 +729,9 @@ func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
} }
value := reflect.New(elemType).Elem() value := reflect.New(elemType).Elem()
d.unmarshal(n.children[i+1], value) d.unmarshal(n.children[i+1], value)
inlineMap.SetMapIndex(name, value) d.setMapIndex(n.children[i+1], inlineMap, name, value)
} else if d.strict {
d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type()))
} }
} }
return true return true

14
vendor/gopkg.in/yaml.v2/emitterc.go generated vendored
View File

@ -2,6 +2,7 @@ package yaml
import ( import (
"bytes" "bytes"
"fmt"
) )
// Flush the buffer if needed. // Flush the buffer if needed.
@ -664,9 +665,8 @@ func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t,
return yaml_emitter_emit_mapping_start(emitter, event) return yaml_emitter_emit_mapping_start(emitter, event)
default: default:
return yaml_emitter_set_emitter_error(emitter, return yaml_emitter_set_emitter_error(emitter,
"expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS") fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ))
} }
return false
} }
// Expect ALIAS. // Expect ALIAS.
@ -843,7 +843,7 @@ func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event
return true return true
} }
// Write an achor. // Write an anchor.
func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool {
if emitter.anchor_data.anchor == nil { if emitter.anchor_data.anchor == nil {
return true return true
@ -995,7 +995,7 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool {
break_space = false break_space = false
space_break = false space_break = false
preceeded_by_whitespace = false preceded_by_whitespace = false
followed_by_whitespace = false followed_by_whitespace = false
previous_space = false previous_space = false
previous_break = false previous_break = false
@ -1017,7 +1017,7 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool {
flow_indicators = true flow_indicators = true
} }
preceeded_by_whitespace = true preceded_by_whitespace = true
for i, w := 0, 0; i < len(value); i += w { for i, w := 0, 0; i < len(value); i += w {
w = width(value[i]) w = width(value[i])
followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w)
@ -1048,7 +1048,7 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool {
block_indicators = true block_indicators = true
} }
case '#': case '#':
if preceeded_by_whitespace { if preceded_by_whitespace {
flow_indicators = true flow_indicators = true
block_indicators = true block_indicators = true
} }
@ -1089,7 +1089,7 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool {
} }
// [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition.
preceeded_by_whitespace = is_blankz(value, i) preceded_by_whitespace = is_blankz(value, i)
} }
emitter.scalar_data.multiline = line_breaks emitter.scalar_data.multiline = line_breaks

132
vendor/gopkg.in/yaml.v2/encode.go generated vendored
View File

@ -3,12 +3,14 @@ package yaml
import ( import (
"encoding" "encoding"
"fmt" "fmt"
"io"
"reflect" "reflect"
"regexp" "regexp"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"unicode/utf8"
) )
type encoder struct { type encoder struct {
@ -16,25 +18,39 @@ type encoder struct {
event yaml_event_t event yaml_event_t
out []byte out []byte
flow bool flow bool
// doneInit holds whether the initial stream_start_event has been
// emitted.
doneInit bool
} }
func newEncoder() (e *encoder) { func newEncoder() *encoder {
e = &encoder{} e := &encoder{}
e.must(yaml_emitter_initialize(&e.emitter)) yaml_emitter_initialize(&e.emitter)
yaml_emitter_set_output_string(&e.emitter, &e.out) yaml_emitter_set_output_string(&e.emitter, &e.out)
yaml_emitter_set_unicode(&e.emitter, true) yaml_emitter_set_unicode(&e.emitter, true)
e.must(yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING))
e.emit()
e.must(yaml_document_start_event_initialize(&e.event, nil, nil, true))
e.emit()
return e return e
} }
func (e *encoder) finish() { func newEncoderWithWriter(w io.Writer) *encoder {
e.must(yaml_document_end_event_initialize(&e.event, true)) e := &encoder{}
yaml_emitter_initialize(&e.emitter)
yaml_emitter_set_output_writer(&e.emitter, w)
yaml_emitter_set_unicode(&e.emitter, true)
return e
}
func (e *encoder) init() {
if e.doneInit {
return
}
yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING)
e.emit() e.emit()
e.doneInit = true
}
func (e *encoder) finish() {
e.emitter.open_ended = false e.emitter.open_ended = false
e.must(yaml_stream_end_event_initialize(&e.event)) yaml_stream_end_event_initialize(&e.event)
e.emit() e.emit()
} }
@ -44,9 +60,7 @@ func (e *encoder) destroy() {
func (e *encoder) emit() { func (e *encoder) emit() {
// This will internally delete the e.event value. // This will internally delete the e.event value.
if !yaml_emitter_emit(&e.emitter, &e.event) && e.event.typ != yaml_DOCUMENT_END_EVENT && e.event.typ != yaml_STREAM_END_EVENT { e.must(yaml_emitter_emit(&e.emitter, &e.event))
e.must(false)
}
} }
func (e *encoder) must(ok bool) { func (e *encoder) must(ok bool) {
@ -59,13 +73,28 @@ func (e *encoder) must(ok bool) {
} }
} }
func (e *encoder) marshalDoc(tag string, in reflect.Value) {
e.init()
yaml_document_start_event_initialize(&e.event, nil, nil, true)
e.emit()
e.marshal(tag, in)
yaml_document_end_event_initialize(&e.event, true)
e.emit()
}
func (e *encoder) marshal(tag string, in reflect.Value) { func (e *encoder) marshal(tag string, in reflect.Value) {
if !in.IsValid() { if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() {
e.nilv() e.nilv()
return return
} }
iface := in.Interface() iface := in.Interface()
if m, ok := iface.(Marshaler); ok { switch m := iface.(type) {
case time.Time, *time.Time:
// Although time.Time implements TextMarshaler,
// we don't want to treat it as a string for YAML
// purposes because YAML has special support for
// timestamps.
case Marshaler:
v, err := m.MarshalYAML() v, err := m.MarshalYAML()
if err != nil { if err != nil {
fail(err) fail(err)
@ -75,31 +104,34 @@ func (e *encoder) marshal(tag string, in reflect.Value) {
return return
} }
in = reflect.ValueOf(v) in = reflect.ValueOf(v)
} else if m, ok := iface.(encoding.TextMarshaler); ok { case encoding.TextMarshaler:
text, err := m.MarshalText() text, err := m.MarshalText()
if err != nil { if err != nil {
fail(err) fail(err)
} }
in = reflect.ValueOf(string(text)) in = reflect.ValueOf(string(text))
case nil:
e.nilv()
return
} }
switch in.Kind() { switch in.Kind() {
case reflect.Interface: case reflect.Interface:
if in.IsNil() {
e.nilv()
} else {
e.marshal(tag, in.Elem()) e.marshal(tag, in.Elem())
}
case reflect.Map: case reflect.Map:
e.mapv(tag, in) e.mapv(tag, in)
case reflect.Ptr: case reflect.Ptr:
if in.IsNil() { if in.Type() == ptrTimeType {
e.nilv() e.timev(tag, in.Elem())
} else { } else {
e.marshal(tag, in.Elem()) e.marshal(tag, in.Elem())
} }
case reflect.Struct: case reflect.Struct:
if in.Type() == timeType {
e.timev(tag, in)
} else {
e.structv(tag, in) e.structv(tag, in)
case reflect.Slice: }
case reflect.Slice, reflect.Array:
if in.Type().Elem() == mapItemType { if in.Type().Elem() == mapItemType {
e.itemsv(tag, in) e.itemsv(tag, in)
} else { } else {
@ -191,10 +223,10 @@ func (e *encoder) mappingv(tag string, f func()) {
e.flow = false e.flow = false
style = yaml_FLOW_MAPPING_STYLE style = yaml_FLOW_MAPPING_STYLE
} }
e.must(yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)
e.emit() e.emit()
f() f()
e.must(yaml_mapping_end_event_initialize(&e.event)) yaml_mapping_end_event_initialize(&e.event)
e.emit() e.emit()
} }
@ -240,23 +272,36 @@ var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0
func (e *encoder) stringv(tag string, in reflect.Value) { func (e *encoder) stringv(tag string, in reflect.Value) {
var style yaml_scalar_style_t var style yaml_scalar_style_t
s := in.String() s := in.String()
rtag, rs := resolve("", s) canUsePlain := true
if rtag == yaml_BINARY_TAG { switch {
if tag == "" || tag == yaml_STR_TAG { case !utf8.ValidString(s):
tag = rtag if tag == yaml_BINARY_TAG {
s = rs.(string)
} else if tag == yaml_BINARY_TAG {
failf("explicitly tagged !!binary data must be base64-encoded") failf("explicitly tagged !!binary data must be base64-encoded")
} else { }
if tag != "" {
failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag))
} }
// It can't be encoded directly as YAML so use a binary tag
// and encode it as base64.
tag = yaml_BINARY_TAG
s = encodeBase64(s)
case tag == "":
// Check to see if it would resolve to a specific
// tag when encoded unquoted. If it doesn't,
// there's no need to quote it.
rtag, _ := resolve("", s)
canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s)
} }
if tag == "" && (rtag != yaml_STR_TAG || isBase60Float(s)) { // Note: it's possible for user code to emit invalid YAML
style = yaml_DOUBLE_QUOTED_SCALAR_STYLE // if they explicitly specify a tag and a string containing
} else if strings.Contains(s, "\n") { // text that's incompatible with that tag.
switch {
case strings.Contains(s, "\n"):
style = yaml_LITERAL_SCALAR_STYLE style = yaml_LITERAL_SCALAR_STYLE
} else { case canUsePlain:
style = yaml_PLAIN_SCALAR_STYLE style = yaml_PLAIN_SCALAR_STYLE
default:
style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
} }
e.emitScalar(s, "", tag, style) e.emitScalar(s, "", tag, style)
} }
@ -281,9 +326,20 @@ func (e *encoder) uintv(tag string, in reflect.Value) {
e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
} }
func (e *encoder) timev(tag string, in reflect.Value) {
t := in.Interface().(time.Time)
s := t.Format(time.RFC3339Nano)
e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
}
func (e *encoder) floatv(tag string, in reflect.Value) { func (e *encoder) floatv(tag string, in reflect.Value) {
// FIXME: Handle 64 bits here. // Issue #352: When formatting, use the precision of the underlying value
s := strconv.FormatFloat(float64(in.Float()), 'g', -1, 32) precision := 64
if in.Kind() == reflect.Float32 {
precision = 32
}
s := strconv.FormatFloat(in.Float(), 'g', -1, precision)
switch s { switch s {
case "+Inf": case "+Inf":
s = ".inf" s = ".inf"

1
vendor/gopkg.in/yaml.v2/parserc.go generated vendored
View File

@ -166,7 +166,6 @@ func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool
default: default:
panic("invalid parser state") panic("invalid parser state")
} }
return false
} }
// Parse the production: // Parse the production:

27
vendor/gopkg.in/yaml.v2/readerc.go generated vendored
View File

@ -93,9 +93,18 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool {
panic("read handler must be set") panic("read handler must be set")
} }
// [Go] This function was changed to guarantee the requested length size at EOF.
// The fact we need to do this is pretty awful, but the description above implies
// for that to be the case, and there are tests
// If the EOF flag is set and the raw buffer is empty, do nothing. // If the EOF flag is set and the raw buffer is empty, do nothing.
if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) {
return true // [Go] ACTUALLY! Read the documentation of this function above.
// This is just broken. To return true, we need to have the
// given length in the buffer. Not doing that means every single
// check that calls this function to make sure the buffer has a
// given length is Go) panicking; or C) accessing invalid memory.
//return true
} }
// Return if the buffer contains enough characters. // Return if the buffer contains enough characters.
@ -247,7 +256,7 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool {
if parser.encoding == yaml_UTF16LE_ENCODING { if parser.encoding == yaml_UTF16LE_ENCODING {
low, high = 0, 1 low, high = 0, 1
} else { } else {
high, low = 1, 0 low, high = 1, 0
} }
// The UTF-16 encoding is not as simple as one might // The UTF-16 encoding is not as simple as one might
@ -357,23 +366,26 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool {
if value <= 0x7F { if value <= 0x7F {
// 0000 0000-0000 007F . 0xxxxxxx // 0000 0000-0000 007F . 0xxxxxxx
parser.buffer[buffer_len+0] = byte(value) parser.buffer[buffer_len+0] = byte(value)
buffer_len += 1
} else if value <= 0x7FF { } else if value <= 0x7FF {
// 0000 0080-0000 07FF . 110xxxxx 10xxxxxx // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx
parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6))
parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F))
buffer_len += 2
} else if value <= 0xFFFF { } else if value <= 0xFFFF {
// 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx
parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12))
parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F))
parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F))
buffer_len += 3
} else { } else {
// 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18))
parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F))
parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F))
parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F))
buffer_len += 4
} }
buffer_len += width
parser.unread++ parser.unread++
} }
@ -386,6 +398,15 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool {
break break
} }
} }
// [Go] Read the documentation of this function above. To return true,
// we need to have the given length in the buffer. Not doing that means
// every single check that calls this function to make sure the buffer
// has a given length is Go) panicking; or C) accessing invalid memory.
// This happens here due to the EOF above breaking early.
for buffer_len < length {
parser.buffer[buffer_len] = 0
buffer_len++
}
parser.buffer = parser.buffer[:buffer_len] parser.buffer = parser.buffer[:buffer_len]
return true return true
} }

83
vendor/gopkg.in/yaml.v2/resolve.go generated vendored
View File

@ -3,9 +3,10 @@ package yaml
import ( import (
"encoding/base64" "encoding/base64"
"math" "math"
"regexp"
"strconv" "strconv"
"strings" "strings"
"unicode/utf8" "time"
) )
type resolveMapItem struct { type resolveMapItem struct {
@ -74,12 +75,14 @@ func longTag(tag string) string {
func resolvableTag(tag string) bool { func resolvableTag(tag string) bool {
switch tag { switch tag {
case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG: case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG:
return true return true
} }
return false return false
} }
var yamlStyleFloat = regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+][0-9]+)?$`)
func resolve(tag string, in string) (rtag string, out interface{}) { func resolve(tag string, in string) (rtag string, out interface{}) {
if !resolvableTag(tag) { if !resolvableTag(tag) {
return tag, in return tag, in
@ -89,6 +92,19 @@ func resolve(tag string, in string) (rtag string, out interface{}) {
switch tag { switch tag {
case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG:
return return
case yaml_FLOAT_TAG:
if rtag == yaml_INT_TAG {
switch v := out.(type) {
case int64:
rtag = yaml_FLOAT_TAG
out = float64(v)
return
case int:
rtag = yaml_FLOAT_TAG
out = float64(v)
return
}
}
} }
failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag))
}() }()
@ -122,6 +138,15 @@ func resolve(tag string, in string) (rtag string, out interface{}) {
case 'D', 'S': case 'D', 'S':
// Int, float, or timestamp. // Int, float, or timestamp.
// Only try values as a timestamp if the value is unquoted or there's an explicit
// !!timestamp tag.
if tag == "" || tag == yaml_TIMESTAMP_TAG {
t, ok := parseTimestamp(in)
if ok {
return yaml_TIMESTAMP_TAG, t
}
}
plain := strings.Replace(in, "_", "", -1) plain := strings.Replace(in, "_", "", -1)
intv, err := strconv.ParseInt(plain, 0, 64) intv, err := strconv.ParseInt(plain, 0, 64)
if err == nil { if err == nil {
@ -135,10 +160,12 @@ func resolve(tag string, in string) (rtag string, out interface{}) {
if err == nil { if err == nil {
return yaml_INT_TAG, uintv return yaml_INT_TAG, uintv
} }
if yamlStyleFloat.MatchString(plain) {
floatv, err := strconv.ParseFloat(plain, 64) floatv, err := strconv.ParseFloat(plain, 64)
if err == nil { if err == nil {
return yaml_FLOAT_TAG, floatv return yaml_FLOAT_TAG, floatv
} }
}
if strings.HasPrefix(plain, "0b") { if strings.HasPrefix(plain, "0b") {
intv, err := strconv.ParseInt(plain[2:], 2, 64) intv, err := strconv.ParseInt(plain[2:], 2, 64)
if err == nil { if err == nil {
@ -153,28 +180,20 @@ func resolve(tag string, in string) (rtag string, out interface{}) {
return yaml_INT_TAG, uintv return yaml_INT_TAG, uintv
} }
} else if strings.HasPrefix(plain, "-0b") { } else if strings.HasPrefix(plain, "-0b") {
intv, err := strconv.ParseInt(plain[3:], 2, 64) intv, err := strconv.ParseInt("-" + plain[3:], 2, 64)
if err == nil { if err == nil {
if intv == int64(int(intv)) { if true || intv == int64(int(intv)) {
return yaml_INT_TAG, -int(intv) return yaml_INT_TAG, int(intv)
} else { } else {
return yaml_INT_TAG, -intv return yaml_INT_TAG, intv
} }
} }
} }
// XXX Handle timestamps here.
default: default:
panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")")
} }
} }
if tag == yaml_BINARY_TAG {
return yaml_BINARY_TAG, in
}
if utf8.ValidString(in) {
return yaml_STR_TAG, in return yaml_STR_TAG, in
}
return yaml_BINARY_TAG, encodeBase64(in)
} }
// encodeBase64 encodes s as base64 that is broken up into multiple lines // encodeBase64 encodes s as base64 that is broken up into multiple lines
@ -201,3 +220,39 @@ func encodeBase64(s string) string {
} }
return string(out[:k]) return string(out[:k])
} }
// This is a subset of the formats allowed by the regular expression
// defined at http://yaml.org/type/timestamp.html.
var allowedTimestampFormats = []string{
"2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields.
"2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t".
"2006-1-2 15:4:5.999999999", // space separated with no time zone
"2006-1-2", // date only
// Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5"
// from the set of examples.
}
// parseTimestamp parses s as a timestamp string and
// returns the timestamp and reports whether it succeeded.
// Timestamp formats are defined at http://yaml.org/type/timestamp.html
func parseTimestamp(s string) (time.Time, bool) {
// TODO write code to check all the formats supported by
// http://yaml.org/type/timestamp.html instead of using time.Parse.
// Quick check: all date formats start with YYYY-.
i := 0
for ; i < len(s); i++ {
if c := s[i]; c < '0' || c > '9' {
break
}
}
if i != 4 || i == len(s) || s[i] != '-' {
return time.Time{}, false
}
for _, format := range allowedTimestampFormats {
if t, err := time.Parse(format, s); err == nil {
return t, true
}
}
return time.Time{}, false
}

42
vendor/gopkg.in/yaml.v2/scannerc.go generated vendored
View File

@ -9,7 +9,7 @@ import (
// ************ // ************
// //
// The following notes assume that you are familiar with the YAML specification // The following notes assume that you are familiar with the YAML specification
// (http://yaml.org/spec/cvs/current.html). We mostly follow it, although in // (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in
// some cases we are less restrictive that it requires. // some cases we are less restrictive that it requires.
// //
// The process of transforming a YAML stream into a sequence of events is // The process of transforming a YAML stream into a sequence of events is
@ -611,7 +611,7 @@ func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, co
if directive { if directive {
context = "while parsing a %TAG directive" context = "while parsing a %TAG directive"
} }
return yaml_parser_set_scanner_error(parser, context, context_mark, "did not find URI escaped octet") return yaml_parser_set_scanner_error(parser, context, context_mark, problem)
} }
func trace(args ...interface{}) func() { func trace(args ...interface{}) func() {
@ -871,12 +871,6 @@ func yaml_parser_save_simple_key(parser *yaml_parser_t) bool {
required := parser.flow_level == 0 && parser.indent == parser.mark.column required := parser.flow_level == 0 && parser.indent == parser.mark.column
// A simple key is required only when it is the first token in the current
// line. Therefore it is always allowed. But we add a check anyway.
if required && !parser.simple_key_allowed {
panic("should not happen")
}
// //
// If the current position may start a simple key, save it. // If the current position may start a simple key, save it.
// //
@ -1546,7 +1540,7 @@ func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool
// Unknown directive. // Unknown directive.
} else { } else {
yaml_parser_set_scanner_error(parser, "while scanning a directive", yaml_parser_set_scanner_error(parser, "while scanning a directive",
start_mark, "found uknown directive name") start_mark, "found unknown directive name")
return false return false
} }
@ -1944,7 +1938,7 @@ func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_ma
} else { } else {
// It's either the '!' tag or not really a tag handle. If it's a %TAG // It's either the '!' tag or not really a tag handle. If it's a %TAG
// directive, it's an error. If it's a tag token, it must be a part of URI. // directive, it's an error. If it's a tag token, it must be a part of URI.
if directive && !(s[0] == '!' && s[1] == 0) { if directive && string(s) != "!" {
yaml_parser_set_scanner_tag_error(parser, directive, yaml_parser_set_scanner_tag_error(parser, directive,
start_mark, "did not find expected '!'") start_mark, "did not find expected '!'")
return false return false
@ -1959,6 +1953,7 @@ func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_ma
func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool {
//size_t length = head ? strlen((char *)head) : 0 //size_t length = head ? strlen((char *)head) : 0
var s []byte var s []byte
hasTag := len(head) > 0
// Copy the head if needed. // Copy the head if needed.
// //
@ -2000,10 +1995,10 @@ func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false return false
} }
hasTag = true
} }
// Check if the tag is non-empty. if !hasTag {
if len(s) == 0 {
yaml_parser_set_scanner_tag_error(parser, directive, yaml_parser_set_scanner_tag_error(parser, directive,
start_mark, "did not find expected tag URI") start_mark, "did not find expected tag URI")
return false return false
@ -2474,6 +2469,10 @@ func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, si
} }
} }
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
// Check if we are at the end of the scalar. // Check if we are at the end of the scalar.
if single { if single {
if parser.buffer[parser.buffer_pos] == '\'' { if parser.buffer[parser.buffer_pos] == '\'' {
@ -2486,10 +2485,6 @@ func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, si
} }
// Consume blank characters. // Consume blank characters.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) {
if is_blank(parser.buffer, parser.buffer_pos) { if is_blank(parser.buffer, parser.buffer_pos) {
// Consume a space or a tab character. // Consume a space or a tab character.
@ -2591,19 +2586,10 @@ func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) b
// Consume non-blank characters. // Consume non-blank characters.
for !is_blankz(parser.buffer, parser.buffer_pos) { for !is_blankz(parser.buffer, parser.buffer_pos) {
// Check for 'x:x' in the flow context. TODO: Fix the test "spec-08-13".
if parser.flow_level > 0 &&
parser.buffer[parser.buffer_pos] == ':' &&
!is_blankz(parser.buffer, parser.buffer_pos+1) {
yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
start_mark, "found unexpected ':'")
return false
}
// Check for indicators that may end a plain scalar. // Check for indicators that may end a plain scalar.
if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) ||
(parser.flow_level > 0 && (parser.flow_level > 0 &&
(parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == ':' || (parser.buffer[parser.buffer_pos] == ',' ||
parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' ||
parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' ||
parser.buffer[parser.buffer_pos] == '}')) { parser.buffer[parser.buffer_pos] == '}')) {
@ -2655,10 +2641,10 @@ func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) b
for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) {
if is_blank(parser.buffer, parser.buffer_pos) { if is_blank(parser.buffer, parser.buffer_pos) {
// Check for tab character that abuse indentation. // Check for tab characters that abuse indentation.
if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) {
yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
start_mark, "found a tab character that violate indentation") start_mark, "found a tab character that violates indentation")
return false return false
} }

9
vendor/gopkg.in/yaml.v2/sorter.go generated vendored
View File

@ -51,6 +51,15 @@ func (l keyList) Less(i, j int) bool {
} }
var ai, bi int var ai, bi int
var an, bn int64 var an, bn int64
if ar[i] == '0' || br[i] == '0' {
for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- {
if ar[j] != '0' {
an = 1
bn = 1
break
}
}
}
for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ {
an = an*10 + int64(ar[ai]-'0') an = an*10 + int64(ar[ai]-'0')
} }

63
vendor/gopkg.in/yaml.v2/writerc.go generated vendored
View File

@ -18,72 +18,9 @@ func yaml_emitter_flush(emitter *yaml_emitter_t) bool {
return true return true
} }
// If the output encoding is UTF-8, we don't need to recode the buffer.
if emitter.encoding == yaml_UTF8_ENCODING {
if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil {
return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
} }
emitter.buffer_pos = 0 emitter.buffer_pos = 0
return true return true
}
// Recode the buffer into the raw buffer.
var low, high int
if emitter.encoding == yaml_UTF16LE_ENCODING {
low, high = 0, 1
} else {
high, low = 1, 0
}
pos := 0
for pos < emitter.buffer_pos {
// See the "reader.c" code for more details on UTF-8 encoding. Note
// that we assume that the buffer contains a valid UTF-8 sequence.
// Read the next UTF-8 character.
octet := emitter.buffer[pos]
var w int
var value rune
switch {
case octet&0x80 == 0x00:
w, value = 1, rune(octet&0x7F)
case octet&0xE0 == 0xC0:
w, value = 2, rune(octet&0x1F)
case octet&0xF0 == 0xE0:
w, value = 3, rune(octet&0x0F)
case octet&0xF8 == 0xF0:
w, value = 4, rune(octet&0x07)
}
for k := 1; k < w; k++ {
octet = emitter.buffer[pos+k]
value = (value << 6) + (rune(octet) & 0x3F)
}
pos += w
// Write the character.
if value < 0x10000 {
var b [2]byte
b[high] = byte(value >> 8)
b[low] = byte(value & 0xFF)
emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1])
} else {
// Write the character using a surrogate pair (check "reader.c").
var b [4]byte
value -= 0x10000
b[high] = byte(0xD8 + (value >> 18))
b[low] = byte((value >> 10) & 0xFF)
b[high+2] = byte(0xDC + ((value >> 8) & 0xFF))
b[low+2] = byte(value & 0xFF)
emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1], b[2], b[3])
}
}
// Write the raw buffer.
if err := emitter.write_handler(emitter, emitter.raw_buffer); err != nil {
return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
}
emitter.buffer_pos = 0
emitter.raw_buffer = emitter.raw_buffer[:0]
return true
} }

138
vendor/gopkg.in/yaml.v2/yaml.go generated vendored
View File

@ -9,6 +9,7 @@ package yaml
import ( import (
"errors" "errors"
"fmt" "fmt"
"io"
"reflect" "reflect"
"strings" "strings"
"sync" "sync"
@ -77,8 +78,65 @@ type Marshaler interface {
// supported tag options. // supported tag options.
// //
func Unmarshal(in []byte, out interface{}) (err error) { func Unmarshal(in []byte, out interface{}) (err error) {
return unmarshal(in, out, false)
}
// UnmarshalStrict is like Unmarshal except that any fields that are found
// in the data that do not have corresponding struct members, or mapping
// keys that are duplicates, will result in
// an error.
func UnmarshalStrict(in []byte, out interface{}) (err error) {
return unmarshal(in, out, true)
}
// A Decorder reads and decodes YAML values from an input stream.
type Decoder struct {
strict bool
parser *parser
}
// NewDecoder returns a new decoder that reads from r.
//
// The decoder introduces its own buffering and may read
// data from r beyond the YAML values requested.
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{
parser: newParserFromReader(r),
}
}
// SetStrict sets whether strict decoding behaviour is enabled when
// decoding items in the data (see UnmarshalStrict). By default, decoding is not strict.
func (dec *Decoder) SetStrict(strict bool) {
dec.strict = strict
}
// Decode reads the next YAML-encoded value from its input
// and stores it in the value pointed to by v.
//
// See the documentation for Unmarshal for details about the
// conversion of YAML into a Go value.
func (dec *Decoder) Decode(v interface{}) (err error) {
d := newDecoder(dec.strict)
defer handleErr(&err) defer handleErr(&err)
d := newDecoder() node := dec.parser.parse()
if node == nil {
return io.EOF
}
out := reflect.ValueOf(v)
if out.Kind() == reflect.Ptr && !out.IsNil() {
out = out.Elem()
}
d.unmarshal(node, out)
if len(d.terrors) > 0 {
return &TypeError{d.terrors}
}
return nil
}
func unmarshal(in []byte, out interface{}, strict bool) (err error) {
defer handleErr(&err)
d := newDecoder(strict)
p := newParser(in) p := newParser(in)
defer p.destroy() defer p.destroy()
node := p.parse() node := p.parse()
@ -99,8 +157,8 @@ func Unmarshal(in []byte, out interface{}) (err error) {
// of the generated document will reflect the structure of the value itself. // of the generated document will reflect the structure of the value itself.
// Maps and pointers (to struct, string, int, etc) are accepted as the in value. // Maps and pointers (to struct, string, int, etc) are accepted as the in value.
// //
// Struct fields are only unmarshalled if they are exported (have an upper case // Struct fields are only marshalled if they are exported (have an upper case
// first letter), and are unmarshalled using the field name lowercased as the // first letter), and are marshalled using the field name lowercased as the
// default key. Custom keys may be defined via the "yaml" name in the field // default key. Custom keys may be defined via the "yaml" name in the field
// tag: the content preceding the first comma is used as the key, and the // tag: the content preceding the first comma is used as the key, and the
// following comma-separated options are used to tweak the marshalling process. // following comma-separated options are used to tweak the marshalling process.
@ -114,7 +172,10 @@ func Unmarshal(in []byte, out interface{}) (err error) {
// //
// omitempty Only include the field if it's not set to the zero // omitempty Only include the field if it's not set to the zero
// value for the type or to empty slices or maps. // value for the type or to empty slices or maps.
// Does not apply to zero valued structs. // Zero valued structs will be omitted if all their public
// fields are zero, unless they implement an IsZero
// method (see the IsZeroer interface type), in which
// case the field will be included if that method returns true.
// //
// flow Marshal using a flow style (useful for structs, // flow Marshal using a flow style (useful for structs,
// sequences and maps). // sequences and maps).
@ -129,7 +190,7 @@ func Unmarshal(in []byte, out interface{}) (err error) {
// For example: // For example:
// //
// type T struct { // type T struct {
// F int "a,omitempty" // F int `yaml:"a,omitempty"`
// B int // B int
// } // }
// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
@ -139,12 +200,47 @@ func Marshal(in interface{}) (out []byte, err error) {
defer handleErr(&err) defer handleErr(&err)
e := newEncoder() e := newEncoder()
defer e.destroy() defer e.destroy()
e.marshal("", reflect.ValueOf(in)) e.marshalDoc("", reflect.ValueOf(in))
e.finish() e.finish()
out = e.out out = e.out
return return
} }
// An Encoder writes YAML values to an output stream.
type Encoder struct {
encoder *encoder
}
// NewEncoder returns a new encoder that writes to w.
// The Encoder should be closed after use to flush all data
// to w.
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{
encoder: newEncoderWithWriter(w),
}
}
// Encode writes the YAML encoding of v to the stream.
// If multiple items are encoded to the stream, the
// second and subsequent document will be preceded
// with a "---" document separator, but the first will not.
//
// See the documentation for Marshal for details about the conversion of Go
// values to YAML.
func (e *Encoder) Encode(v interface{}) (err error) {
defer handleErr(&err)
e.encoder.marshalDoc("", reflect.ValueOf(v))
return nil
}
// Close closes the encoder by writing any remaining data.
// It does not write a stream terminating string "...".
func (e *Encoder) Close() (err error) {
defer handleErr(&err)
e.encoder.finish()
return nil
}
func handleErr(err *error) { func handleErr(err *error) {
if v := recover(); v != nil { if v := recover(); v != nil {
if e, ok := v.(yamlError); ok { if e, ok := v.(yamlError); ok {
@ -200,6 +296,9 @@ type fieldInfo struct {
Num int Num int
OmitEmpty bool OmitEmpty bool
Flow bool Flow bool
// Id holds the unique field identifier, so we can cheaply
// check for field duplicates without maintaining an extra map.
Id int
// Inline holds the field index if the field is part of an inlined struct. // Inline holds the field index if the field is part of an inlined struct.
Inline []int Inline []int
@ -222,7 +321,7 @@ func getStructInfo(st reflect.Type) (*structInfo, error) {
inlineMap := -1 inlineMap := -1
for i := 0; i != n; i++ { for i := 0; i != n; i++ {
field := st.Field(i) field := st.Field(i)
if field.PkgPath != "" { if field.PkgPath != "" && !field.Anonymous {
continue // Private field continue // Private field
} }
@ -279,6 +378,7 @@ func getStructInfo(st reflect.Type) (*structInfo, error) {
} else { } else {
finfo.Inline = append([]int{i}, finfo.Inline...) finfo.Inline = append([]int{i}, finfo.Inline...)
} }
finfo.Id = len(fieldsList)
fieldsMap[finfo.Key] = finfo fieldsMap[finfo.Key] = finfo
fieldsList = append(fieldsList, finfo) fieldsList = append(fieldsList, finfo)
} }
@ -300,11 +400,16 @@ func getStructInfo(st reflect.Type) (*structInfo, error) {
return nil, errors.New(msg) return nil, errors.New(msg)
} }
info.Id = len(fieldsList)
fieldsList = append(fieldsList, info) fieldsList = append(fieldsList, info)
fieldsMap[info.Key] = info fieldsMap[info.Key] = info
} }
sinfo = &structInfo{fieldsMap, fieldsList, inlineMap} sinfo = &structInfo{
FieldsMap: fieldsMap,
FieldsList: fieldsList,
InlineMap: inlineMap,
}
fieldMapMutex.Lock() fieldMapMutex.Lock()
structMap[st] = sinfo structMap[st] = sinfo
@ -312,8 +417,23 @@ func getStructInfo(st reflect.Type) (*structInfo, error) {
return sinfo, nil return sinfo, nil
} }
// IsZeroer is used to check whether an object is zero to
// determine whether it should be omitted when marshaling
// with the omitempty flag. One notable implementation
// is time.Time.
type IsZeroer interface {
IsZero() bool
}
func isZero(v reflect.Value) bool { func isZero(v reflect.Value) bool {
switch v.Kind() { kind := v.Kind()
if z, ok := v.Interface().(IsZeroer); ok {
if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() {
return true
}
return z.IsZero()
}
switch kind {
case reflect.String: case reflect.String:
return len(v.String()) == 0 return len(v.String()) == 0
case reflect.Interface, reflect.Ptr: case reflect.Interface, reflect.Ptr:

28
vendor/gopkg.in/yaml.v2/yamlh.go generated vendored
View File

@ -1,6 +1,7 @@
package yaml package yaml
import ( import (
"fmt"
"io" "io"
) )
@ -239,6 +240,27 @@ const (
yaml_MAPPING_END_EVENT // A MAPPING-END event. yaml_MAPPING_END_EVENT // A MAPPING-END event.
) )
var eventStrings = []string{
yaml_NO_EVENT: "none",
yaml_STREAM_START_EVENT: "stream start",
yaml_STREAM_END_EVENT: "stream end",
yaml_DOCUMENT_START_EVENT: "document start",
yaml_DOCUMENT_END_EVENT: "document end",
yaml_ALIAS_EVENT: "alias",
yaml_SCALAR_EVENT: "scalar",
yaml_SEQUENCE_START_EVENT: "sequence start",
yaml_SEQUENCE_END_EVENT: "sequence end",
yaml_MAPPING_START_EVENT: "mapping start",
yaml_MAPPING_END_EVENT: "mapping end",
}
func (e yaml_event_type_t) String() string {
if e < 0 || int(e) >= len(eventStrings) {
return fmt.Sprintf("unknown event %d", e)
}
return eventStrings[e]
}
// The event structure. // The event structure.
type yaml_event_t struct { type yaml_event_t struct {
@ -508,7 +530,7 @@ type yaml_parser_t struct {
problem string // Error description. problem string // Error description.
// The byte about which the problem occured. // The byte about which the problem occurred.
problem_offset int problem_offset int
problem_value int problem_value int
problem_mark yaml_mark_t problem_mark yaml_mark_t
@ -521,7 +543,7 @@ type yaml_parser_t struct {
read_handler yaml_read_handler_t // Read handler. read_handler yaml_read_handler_t // Read handler.
input_file io.Reader // File input data. input_reader io.Reader // File input data.
input []byte // String input data. input []byte // String input data.
input_pos int input_pos int
@ -632,7 +654,7 @@ type yaml_emitter_t struct {
write_handler yaml_write_handler_t // Write handler. write_handler yaml_write_handler_t // Write handler.
output_buffer *[]byte // String output data. output_buffer *[]byte // String output data.
output_file io.Writer // File output data. output_writer io.Writer // File output data.
buffer []byte // The working buffer. buffer []byte // The working buffer.
buffer_pos int // The current position of the buffer. buffer_pos int // The current position of the buffer.

View File

@ -78,4 +78,23 @@ const (
// //
// Not all cloud providers support this annotation, though AWS & GCE do. // Not all cloud providers support this annotation, though AWS & GCE do.
AnnotationLoadBalancerSourceRangesKey = "service.beta.kubernetes.io/load-balancer-source-ranges" AnnotationLoadBalancerSourceRangesKey = "service.beta.kubernetes.io/load-balancer-source-ranges"
// EndpointsLastChangeTriggerTime is the annotation key, set for endpoints objects, that
// represents the timestamp (stored as RFC 3339 date-time string, e.g. '2018-10-22T19:32:52.1Z')
// of the last change, of some Pod or Service object, that triggered the endpoints object change.
// In other words, if a Pod / Service changed at time T0, that change was observed by endpoints
// controller at T1, and the Endpoints object was changed at T2, the
// EndpointsLastChangeTriggerTime would be set to T0.
//
// The "endpoints change trigger" here means any Pod or Service change that resulted in the
// Endpoints object change.
//
// Given the definition of the "endpoints change trigger", please note that this annotation will
// be set ONLY for endpoints object changes triggered by either Pod or Service change. If the
// Endpoints object changes due to other reasons, this annotation won't be set (or updated if it's
// already set).
//
// This annotation will be used to compute the in-cluster network programming latency SLI, see
// https://github.com/kubernetes/community/blob/master/sig-scalability/slos/network_programming_latency.md
EndpointsLastChangeTriggerTime = "endpoints.kubernetes.io/last-change-trigger-time"
) )

File diff suppressed because it is too large Load Diff

View File

@ -606,6 +606,9 @@ message Container {
// +optional // +optional
// +patchMergeKey=containerPort // +patchMergeKey=containerPort
// +patchStrategy=merge // +patchStrategy=merge
// +listType=map
// +listMapKey=containerPort
// +listMapKey=protocol
repeated ContainerPort ports = 6; repeated ContainerPort ports = 6;
// List of sources to populate environment variables in the container. // List of sources to populate environment variables in the container.
@ -638,7 +641,7 @@ message Container {
repeated VolumeMount volumeMounts = 9; repeated VolumeMount volumeMounts = 9;
// volumeDevices is the list of block devices to be used by the container. // volumeDevices is the list of block devices to be used by the container.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +patchMergeKey=devicePath // +patchMergeKey=devicePath
// +patchStrategy=merge // +patchStrategy=merge
// +optional // +optional
@ -1370,6 +1373,30 @@ message GitRepoVolumeSource {
optional string directory = 3; optional string directory = 3;
} }
// Represents a Glusterfs mount that lasts the lifetime of a pod.
// Glusterfs volumes do not support ownership management or SELinux relabeling.
message GlusterfsPersistentVolumeSource {
// EndpointsName is the endpoint name that details Glusterfs topology.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
optional string endpoints = 1;
// Path is the Glusterfs volume path.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
optional string path = 2;
// ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions.
// Defaults to false.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
optional bool readOnly = 3;
// EndpointsNamespace is the namespace that contains Glusterfs endpoint.
// If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
optional string endpointsNamespace = 4;
}
// Represents a Glusterfs mount that lasts the lifetime of a pod. // Represents a Glusterfs mount that lasts the lifetime of a pod.
// Glusterfs volumes do not support ownership management or SELinux relabeling. // Glusterfs volumes do not support ownership management or SELinux relabeling.
message GlusterfsVolumeSource { message GlusterfsVolumeSource {
@ -2293,7 +2320,7 @@ message PersistentVolumeClaimSpec {
// volumeMode defines what type of volume is required by the claim. // volumeMode defines what type of volume is required by the claim.
// Value of Filesystem is implied when not included in claim spec. // Value of Filesystem is implied when not included in claim spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
optional string volumeMode = 6; optional string volumeMode = 6;
@ -2386,7 +2413,7 @@ message PersistentVolumeSource {
// exposed to the pod. Provisioned by an admin. // exposed to the pod. Provisioned by an admin.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md // More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md
// +optional // +optional
optional GlusterfsVolumeSource glusterfs = 4; optional GlusterfsPersistentVolumeSource glusterfs = 4;
// NFS represents an NFS mount on the host. Provisioned by an admin. // NFS represents an NFS mount on the host. Provisioned by an admin.
// More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs // More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
@ -2509,7 +2536,7 @@ message PersistentVolumeSpec {
// volumeMode defines if a volume is intended to be used with a formatted filesystem // volumeMode defines if a volume is intended to be used with a formatted filesystem
// or to remain in raw block state. Value of Filesystem is implied when not included in spec. // or to remain in raw block state. Value of Filesystem is implied when not included in spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
optional string volumeMode = 8; optional string volumeMode = 8;
@ -3126,6 +3153,11 @@ message PodSpec {
// This is an alpha feature and may change in the future. // This is an alpha feature and may change in the future.
// +optional // +optional
optional string runtimeClassName = 29; optional string runtimeClassName = 29;
// EnableServiceLinks indicates whether information about services should be injected into pod's
// environment variables, matching the syntax of Docker links.
// +optional
optional bool enableServiceLinks = 30;
} }
// PodStatus represents information about the status of a pod. Status may trail the actual // PodStatus represents information about the status of a pod. Status may trail the actual

54
vendor/k8s.io/api/core/v1/types.go generated vendored
View File

@ -191,7 +191,7 @@ type PersistentVolumeSource struct {
// exposed to the pod. Provisioned by an admin. // exposed to the pod. Provisioned by an admin.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md // More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md
// +optional // +optional
Glusterfs *GlusterfsVolumeSource `json:"glusterfs,omitempty" protobuf:"bytes,4,opt,name=glusterfs"` Glusterfs *GlusterfsPersistentVolumeSource `json:"glusterfs,omitempty" protobuf:"bytes,4,opt,name=glusterfs"`
// NFS represents an NFS mount on the host. Provisioned by an admin. // NFS represents an NFS mount on the host. Provisioned by an admin.
// More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs // More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
// +optional // +optional
@ -326,7 +326,7 @@ type PersistentVolumeSpec struct {
MountOptions []string `json:"mountOptions,omitempty" protobuf:"bytes,7,opt,name=mountOptions"` MountOptions []string `json:"mountOptions,omitempty" protobuf:"bytes,7,opt,name=mountOptions"`
// volumeMode defines if a volume is intended to be used with a formatted filesystem // volumeMode defines if a volume is intended to be used with a formatted filesystem
// or to remain in raw block state. Value of Filesystem is implied when not included in spec. // or to remain in raw block state. Value of Filesystem is implied when not included in spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
VolumeMode *PersistentVolumeMode `json:"volumeMode,omitempty" protobuf:"bytes,8,opt,name=volumeMode,casttype=PersistentVolumeMode"` VolumeMode *PersistentVolumeMode `json:"volumeMode,omitempty" protobuf:"bytes,8,opt,name=volumeMode,casttype=PersistentVolumeMode"`
// NodeAffinity defines constraints that limit what nodes this volume can be accessed from. // NodeAffinity defines constraints that limit what nodes this volume can be accessed from.
@ -455,7 +455,7 @@ type PersistentVolumeClaimSpec struct {
StorageClassName *string `json:"storageClassName,omitempty" protobuf:"bytes,5,opt,name=storageClassName"` StorageClassName *string `json:"storageClassName,omitempty" protobuf:"bytes,5,opt,name=storageClassName"`
// volumeMode defines what type of volume is required by the claim. // volumeMode defines what type of volume is required by the claim.
// Value of Filesystem is implied when not included in claim spec. // Value of Filesystem is implied when not included in claim spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
VolumeMode *PersistentVolumeMode `json:"volumeMode,omitempty" protobuf:"bytes,6,opt,name=volumeMode,casttype=PersistentVolumeMode"` VolumeMode *PersistentVolumeMode `json:"volumeMode,omitempty" protobuf:"bytes,6,opt,name=volumeMode,casttype=PersistentVolumeMode"`
// This field requires the VolumeSnapshotDataSource alpha feature gate to be // This field requires the VolumeSnapshotDataSource alpha feature gate to be
@ -636,6 +636,30 @@ type GlusterfsVolumeSource struct {
ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,3,opt,name=readOnly"` ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,3,opt,name=readOnly"`
} }
// Represents a Glusterfs mount that lasts the lifetime of a pod.
// Glusterfs volumes do not support ownership management or SELinux relabeling.
type GlusterfsPersistentVolumeSource struct {
// EndpointsName is the endpoint name that details Glusterfs topology.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
EndpointsName string `json:"endpoints" protobuf:"bytes,1,opt,name=endpoints"`
// Path is the Glusterfs volume path.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
Path string `json:"path" protobuf:"bytes,2,opt,name=path"`
// ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions.
// Defaults to false.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,3,opt,name=readOnly"`
// EndpointsNamespace is the namespace that contains Glusterfs endpoint.
// If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
EndpointsNamespace *string `json:"endpointsNamespace,omitempty" protobuf:"bytes,4,opt,name=endpointsNamespace"`
}
// Represents a Rados Block Device mount that lasts the lifetime of a pod. // Represents a Rados Block Device mount that lasts the lifetime of a pod.
// RBD volumes support ownership management and SELinux relabeling. // RBD volumes support ownership management and SELinux relabeling.
type RBDVolumeSource struct { type RBDVolumeSource struct {
@ -2060,6 +2084,9 @@ type Container struct {
// +optional // +optional
// +patchMergeKey=containerPort // +patchMergeKey=containerPort
// +patchStrategy=merge // +patchStrategy=merge
// +listType=map
// +listMapKey=containerPort
// +listMapKey=protocol
Ports []ContainerPort `json:"ports,omitempty" patchStrategy:"merge" patchMergeKey:"containerPort" protobuf:"bytes,6,rep,name=ports"` Ports []ContainerPort `json:"ports,omitempty" patchStrategy:"merge" patchMergeKey:"containerPort" protobuf:"bytes,6,rep,name=ports"`
// List of sources to populate environment variables in the container. // List of sources to populate environment variables in the container.
// The keys defined within a source must be a C_IDENTIFIER. All invalid keys // The keys defined within a source must be a C_IDENTIFIER. All invalid keys
@ -2087,7 +2114,7 @@ type Container struct {
// +patchStrategy=merge // +patchStrategy=merge
VolumeMounts []VolumeMount `json:"volumeMounts,omitempty" patchStrategy:"merge" patchMergeKey:"mountPath" protobuf:"bytes,9,rep,name=volumeMounts"` VolumeMounts []VolumeMount `json:"volumeMounts,omitempty" patchStrategy:"merge" patchMergeKey:"mountPath" protobuf:"bytes,9,rep,name=volumeMounts"`
// volumeDevices is the list of block devices to be used by the container. // volumeDevices is the list of block devices to be used by the container.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +patchMergeKey=devicePath // +patchMergeKey=devicePath
// +patchStrategy=merge // +patchStrategy=merge
// +optional // +optional
@ -2891,8 +2918,17 @@ type PodSpec struct {
// This is an alpha feature and may change in the future. // This is an alpha feature and may change in the future.
// +optional // +optional
RuntimeClassName *string `json:"runtimeClassName,omitempty" protobuf:"bytes,29,opt,name=runtimeClassName"` RuntimeClassName *string `json:"runtimeClassName,omitempty" protobuf:"bytes,29,opt,name=runtimeClassName"`
// EnableServiceLinks indicates whether information about services should be injected into pod's
// environment variables, matching the syntax of Docker links.
// +optional
EnableServiceLinks *bool `json:"enableServiceLinks,omitempty" protobuf:"varint,30,opt,name=enableServiceLinks"`
} }
const (
// The default value for enableServiceLinks attribute.
DefaultEnableServiceLinks = true
)
// HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the // HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the
// pod's hosts file. // pod's hosts file.
type HostAlias struct { type HostAlias struct {
@ -3273,8 +3309,8 @@ type ReplicationControllerCondition struct {
} }
// +genclient // +genclient
// +genclient:method=GetScale,verb=get,subresource=scale,result=k8s.io/api/extensions/v1beta1.Scale // +genclient:method=GetScale,verb=get,subresource=scale,result=k8s.io/api/autoscaling/v1.Scale
// +genclient:method=UpdateScale,verb=update,subresource=scale,input=k8s.io/api/extensions/v1beta1.Scale,result=k8s.io/api/extensions/v1beta1.Scale // +genclient:method=UpdateScale,verb=update,subresource=scale,input=k8s.io/api/autoscaling/v1.Scale,result=k8s.io/api/autoscaling/v1.Scale
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ReplicationController represents the configuration of a replication controller. // ReplicationController represents the configuration of a replication controller.
@ -4987,6 +5023,10 @@ const (
TLSCertKey = "tls.crt" TLSCertKey = "tls.crt"
// TLSPrivateKeyKey is the key for the private key field in a TLS secret. // TLSPrivateKeyKey is the key for the private key field in a TLS secret.
TLSPrivateKeyKey = "tls.key" TLSPrivateKeyKey = "tls.key"
// SecretTypeBootstrapToken is used during the automated bootstrap process (first
// implemented by kubeadm). It stores tokens that are used to sign well known
// ConfigMaps. They are used for authn.
SecretTypeBootstrapToken SecretType = "bootstrap.kubernetes.io/token"
) )
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
@ -5210,7 +5250,7 @@ type SecurityContext struct {
// readonly paths and masked paths. // readonly paths and masked paths.
// This requires the ProcMountType feature flag to be enabled. // This requires the ProcMountType feature flag to be enabled.
// +optional // +optional
ProcMount *ProcMountType `json:"procMount,omitEmpty" protobuf:"bytes,9,opt,name=procMount"` ProcMount *ProcMountType `json:"procMount,omitempty" protobuf:"bytes,9,opt,name=procMount"`
} }
type ProcMountType string type ProcMountType string

View File

@ -321,7 +321,7 @@ var map_Container = map[string]string{
"env": "List of environment variables to set in the container. Cannot be updated.", "env": "List of environment variables to set in the container. Cannot be updated.",
"resources": "Compute Resources required by this container. Cannot be updated. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/", "resources": "Compute Resources required by this container. Cannot be updated. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/",
"volumeMounts": "Pod volumes to mount into the container's filesystem. Cannot be updated.", "volumeMounts": "Pod volumes to mount into the container's filesystem. Cannot be updated.",
"volumeDevices": "volumeDevices is the list of block devices to be used by the container. This is an alpha feature and may change in the future.", "volumeDevices": "volumeDevices is the list of block devices to be used by the container. This is a beta feature.",
"livenessProbe": "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", "livenessProbe": "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes",
"readinessProbe": "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", "readinessProbe": "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes",
"lifecycle": "Actions that the management system should take in response to container lifecycle events. Cannot be updated.", "lifecycle": "Actions that the management system should take in response to container lifecycle events. Cannot be updated.",
@ -695,6 +695,18 @@ func (GitRepoVolumeSource) SwaggerDoc() map[string]string {
return map_GitRepoVolumeSource return map_GitRepoVolumeSource
} }
var map_GlusterfsPersistentVolumeSource = map[string]string{
"": "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.",
"endpoints": "EndpointsName is the endpoint name that details Glusterfs topology. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod",
"path": "Path is the Glusterfs volume path. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod",
"readOnly": "ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod",
"endpointsNamespace": "EndpointsNamespace is the namespace that contains Glusterfs endpoint. If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod",
}
func (GlusterfsPersistentVolumeSource) SwaggerDoc() map[string]string {
return map_GlusterfsPersistentVolumeSource
}
var map_GlusterfsVolumeSource = map[string]string{ var map_GlusterfsVolumeSource = map[string]string{
"": "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.", "": "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.",
"endpoints": "EndpointsName is the endpoint name that details Glusterfs topology. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", "endpoints": "EndpointsName is the endpoint name that details Glusterfs topology. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod",
@ -1210,7 +1222,7 @@ var map_PersistentVolumeClaimSpec = map[string]string{
"resources": "Resources represents the minimum resources the volume should have. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources", "resources": "Resources represents the minimum resources the volume should have. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources",
"volumeName": "VolumeName is the binding reference to the PersistentVolume backing this claim.", "volumeName": "VolumeName is the binding reference to the PersistentVolume backing this claim.",
"storageClassName": "Name of the StorageClass required by the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1", "storageClassName": "Name of the StorageClass required by the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1",
"volumeMode": "volumeMode defines what type of volume is required by the claim. Value of Filesystem is implied when not included in claim spec. This is an alpha feature and may change in the future.", "volumeMode": "volumeMode defines what type of volume is required by the claim. Value of Filesystem is implied when not included in claim spec. This is a beta feature.",
"dataSource": "This field requires the VolumeSnapshotDataSource alpha feature gate to be enabled and currently VolumeSnapshot is the only supported data source. If the provisioner can support VolumeSnapshot data source, it will create a new volume and data will be restored to the volume at the same time. If the provisioner does not support VolumeSnapshot data source, volume will not be created and the failure will be reported as an event. In the future, we plan to support more data source types and the behavior of the provisioner may change.", "dataSource": "This field requires the VolumeSnapshotDataSource alpha feature gate to be enabled and currently VolumeSnapshot is the only supported data source. If the provisioner can support VolumeSnapshot data source, it will create a new volume and data will be restored to the volume at the same time. If the provisioner does not support VolumeSnapshot data source, volume will not be created and the failure will be reported as an event. In the future, we plan to support more data source types and the behavior of the provisioner may change.",
} }
@ -1288,7 +1300,7 @@ var map_PersistentVolumeSpec = map[string]string{
"persistentVolumeReclaimPolicy": "What happens to a persistent volume when released from its claim. Valid options are Retain (default for manually created PersistentVolumes), Delete (default for dynamically provisioned PersistentVolumes), and Recycle (deprecated). Recycle must be supported by the volume plugin underlying this PersistentVolume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#reclaiming", "persistentVolumeReclaimPolicy": "What happens to a persistent volume when released from its claim. Valid options are Retain (default for manually created PersistentVolumes), Delete (default for dynamically provisioned PersistentVolumes), and Recycle (deprecated). Recycle must be supported by the volume plugin underlying this PersistentVolume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#reclaiming",
"storageClassName": "Name of StorageClass to which this persistent volume belongs. Empty value means that this volume does not belong to any StorageClass.", "storageClassName": "Name of StorageClass to which this persistent volume belongs. Empty value means that this volume does not belong to any StorageClass.",
"mountOptions": "A list of mount options, e.g. [\"ro\", \"soft\"]. Not validated - mount will simply fail if one is invalid. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes/#mount-options", "mountOptions": "A list of mount options, e.g. [\"ro\", \"soft\"]. Not validated - mount will simply fail if one is invalid. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes/#mount-options",
"volumeMode": "volumeMode defines if a volume is intended to be used with a formatted filesystem or to remain in raw block state. Value of Filesystem is implied when not included in spec. This is an alpha feature and may change in the future.", "volumeMode": "volumeMode defines if a volume is intended to be used with a formatted filesystem or to remain in raw block state. Value of Filesystem is implied when not included in spec. This is a beta feature.",
"nodeAffinity": "NodeAffinity defines constraints that limit what nodes this volume can be accessed from. This field influences the scheduling of pods that use this volume.", "nodeAffinity": "NodeAffinity defines constraints that limit what nodes this volume can be accessed from. This field influences the scheduling of pods that use this volume.",
} }
@ -1528,6 +1540,7 @@ var map_PodSpec = map[string]string{
"dnsConfig": "Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy.", "dnsConfig": "Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy.",
"readinessGates": "If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://github.com/kubernetes/community/blob/master/keps/sig-network/0007-pod-ready%2B%2B.md", "readinessGates": "If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://github.com/kubernetes/community/blob/master/keps/sig-network/0007-pod-ready%2B%2B.md",
"runtimeClassName": "RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://github.com/kubernetes/community/blob/master/keps/sig-node/0014-runtime-class.md This is an alpha feature and may change in the future.", "runtimeClassName": "RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://github.com/kubernetes/community/blob/master/keps/sig-node/0014-runtime-class.md This is an alpha feature and may change in the future.",
"enableServiceLinks": "EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links.",
} }
func (PodSpec) SwaggerDoc() map[string]string { func (PodSpec) SwaggerDoc() map[string]string {

View File

@ -1498,6 +1498,27 @@ func (in *GitRepoVolumeSource) DeepCopy() *GitRepoVolumeSource {
return out return out
} }
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GlusterfsPersistentVolumeSource) DeepCopyInto(out *GlusterfsPersistentVolumeSource) {
*out = *in
if in.EndpointsNamespace != nil {
in, out := &in.EndpointsNamespace, &out.EndpointsNamespace
*out = new(string)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GlusterfsPersistentVolumeSource.
func (in *GlusterfsPersistentVolumeSource) DeepCopy() *GlusterfsPersistentVolumeSource {
if in == nil {
return nil
}
out := new(GlusterfsPersistentVolumeSource)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GlusterfsVolumeSource) DeepCopyInto(out *GlusterfsVolumeSource) { func (in *GlusterfsVolumeSource) DeepCopyInto(out *GlusterfsVolumeSource) {
*out = *in *out = *in
@ -2806,8 +2827,8 @@ func (in *PersistentVolumeSource) DeepCopyInto(out *PersistentVolumeSource) {
} }
if in.Glusterfs != nil { if in.Glusterfs != nil {
in, out := &in.Glusterfs, &out.Glusterfs in, out := &in.Glusterfs, &out.Glusterfs
*out = new(GlusterfsVolumeSource) *out = new(GlusterfsPersistentVolumeSource)
**out = **in (*in).DeepCopyInto(*out)
} }
if in.NFS != nil { if in.NFS != nil {
in, out := &in.NFS, &out.NFS in, out := &in.NFS, &out.NFS
@ -3554,6 +3575,11 @@ func (in *PodSpec) DeepCopyInto(out *PodSpec) {
*out = new(string) *out = new(string)
**out = **in **out = **in
} }
if in.EnableServiceLinks != nil {
in, out := &in.EnableServiceLinks, &out.EnableServiceLinks
*out = new(bool)
**out = **in
}
return return
} }

View File

@ -20,6 +20,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"reflect"
"strings" "strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -82,7 +83,20 @@ func (u *UnexpectedObjectError) Error() string {
func FromObject(obj runtime.Object) error { func FromObject(obj runtime.Object) error {
switch t := obj.(type) { switch t := obj.(type) {
case *metav1.Status: case *metav1.Status:
return &StatusError{*t} return &StatusError{ErrStatus: *t}
case runtime.Unstructured:
var status metav1.Status
obj := t.UnstructuredContent()
if !reflect.DeepEqual(obj["kind"], "Status") {
break
}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(t.UnstructuredContent(), &status); err != nil {
return err
}
if status.APIVersion != "v1" && status.APIVersion != "meta.k8s.io/v1" {
break
}
return &StatusError{ErrStatus: status}
} }
return &UnexpectedObjectError{obj} return &UnexpectedObjectError{obj}
} }

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/api/resource/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/api/resource/generated.proto
// DO NOT EDIT!
/* /*
Package resource is a generated protocol buffer package. Package resource is a generated protocol buffer package.

View File

@ -19,4 +19,5 @@ limitations under the License.
// +k8s:defaulter-gen=TypeMeta // +k8s:defaulter-gen=TypeMeta
// +groupName=meta.k8s.io // +groupName=meta.k8s.io
package v1 // import "k8s.io/apimachinery/pkg/apis/meta/v1" package v1 // import "k8s.io/apimachinery/pkg/apis/meta/v1"

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto
// DO NOT EDIT!
/* /*
Package v1 is a generated protocol buffer package. Package v1 is a generated protocol buffer package.
@ -1768,24 +1767,6 @@ func (m *WatchEvent) MarshalTo(dAtA []byte) (int, error) {
return i, nil return i, nil
} }
func encodeFixed64Generated(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
dAtA[offset+4] = uint8(v >> 32)
dAtA[offset+5] = uint8(v >> 40)
dAtA[offset+6] = uint8(v >> 48)
dAtA[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32Generated(dAtA []byte, offset int, v uint32) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 { for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80) dAtA[offset] = uint8(v&0x7f | 0x80)
@ -5043,7 +5024,14 @@ func (m *LabelSelector) Unmarshal(dAtA []byte) error {
if postIndex > l { if postIndex > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
var keykey uint64 if m.MatchLabels == nil {
m.MatchLabels = make(map[string]string)
}
var mapkey string
var mapvalue string
for iNdEx < postIndex {
entryPreIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
return ErrIntOverflowGenerated return ErrIntOverflowGenerated
@ -5053,11 +5041,13 @@ func (m *LabelSelector) Unmarshal(dAtA []byte) error {
} }
b := dAtA[iNdEx] b := dAtA[iNdEx]
iNdEx++ iNdEx++
keykey |= (uint64(b) & 0x7F) << shift wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 { if b < 0x80 {
break break
} }
} }
fieldNum := int32(wire >> 3)
if fieldNum == 1 {
var stringLenmapkey uint64 var stringLenmapkey uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -5081,27 +5071,9 @@ func (m *LabelSelector) Unmarshal(dAtA []byte) error {
if postStringIndexmapkey > l { if postStringIndexmapkey > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapkey := string(dAtA[iNdEx:postStringIndexmapkey]) mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
iNdEx = postStringIndexmapkey iNdEx = postStringIndexmapkey
if m.MatchLabels == nil { } else if fieldNum == 2 {
m.MatchLabels = make(map[string]string)
}
if iNdEx < postIndex {
var valuekey uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
valuekey |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
var stringLenmapvalue uint64 var stringLenmapvalue uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -5125,13 +5097,24 @@ func (m *LabelSelector) Unmarshal(dAtA []byte) error {
if postStringIndexmapvalue > l { if postStringIndexmapvalue > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue]) mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue])
iNdEx = postStringIndexmapvalue iNdEx = postStringIndexmapvalue
m.MatchLabels[mapkey] = mapvalue
} else { } else {
var mapvalue string iNdEx = entryPreIndex
m.MatchLabels[mapkey] = mapvalue skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
} }
if skippy < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > postIndex {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
m.MatchLabels[mapkey] = mapvalue
iNdEx = postIndex iNdEx = postIndex
case 2: case 2:
if wireType != 2 { if wireType != 2 {
@ -6146,7 +6129,14 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postIndex > l { if postIndex > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
var keykey uint64 if m.Labels == nil {
m.Labels = make(map[string]string)
}
var mapkey string
var mapvalue string
for iNdEx < postIndex {
entryPreIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
return ErrIntOverflowGenerated return ErrIntOverflowGenerated
@ -6156,11 +6146,13 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
} }
b := dAtA[iNdEx] b := dAtA[iNdEx]
iNdEx++ iNdEx++
keykey |= (uint64(b) & 0x7F) << shift wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 { if b < 0x80 {
break break
} }
} }
fieldNum := int32(wire >> 3)
if fieldNum == 1 {
var stringLenmapkey uint64 var stringLenmapkey uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -6184,27 +6176,9 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postStringIndexmapkey > l { if postStringIndexmapkey > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapkey := string(dAtA[iNdEx:postStringIndexmapkey]) mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
iNdEx = postStringIndexmapkey iNdEx = postStringIndexmapkey
if m.Labels == nil { } else if fieldNum == 2 {
m.Labels = make(map[string]string)
}
if iNdEx < postIndex {
var valuekey uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
valuekey |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
var stringLenmapvalue uint64 var stringLenmapvalue uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -6228,13 +6202,24 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postStringIndexmapvalue > l { if postStringIndexmapvalue > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue]) mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue])
iNdEx = postStringIndexmapvalue iNdEx = postStringIndexmapvalue
m.Labels[mapkey] = mapvalue
} else { } else {
var mapvalue string iNdEx = entryPreIndex
m.Labels[mapkey] = mapvalue skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
} }
if skippy < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > postIndex {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
m.Labels[mapkey] = mapvalue
iNdEx = postIndex iNdEx = postIndex
case 12: case 12:
if wireType != 2 { if wireType != 2 {
@ -6262,7 +6247,14 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postIndex > l { if postIndex > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
var keykey uint64 if m.Annotations == nil {
m.Annotations = make(map[string]string)
}
var mapkey string
var mapvalue string
for iNdEx < postIndex {
entryPreIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
return ErrIntOverflowGenerated return ErrIntOverflowGenerated
@ -6272,11 +6264,13 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
} }
b := dAtA[iNdEx] b := dAtA[iNdEx]
iNdEx++ iNdEx++
keykey |= (uint64(b) & 0x7F) << shift wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 { if b < 0x80 {
break break
} }
} }
fieldNum := int32(wire >> 3)
if fieldNum == 1 {
var stringLenmapkey uint64 var stringLenmapkey uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -6300,27 +6294,9 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postStringIndexmapkey > l { if postStringIndexmapkey > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapkey := string(dAtA[iNdEx:postStringIndexmapkey]) mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
iNdEx = postStringIndexmapkey iNdEx = postStringIndexmapkey
if m.Annotations == nil { } else if fieldNum == 2 {
m.Annotations = make(map[string]string)
}
if iNdEx < postIndex {
var valuekey uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGenerated
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
valuekey |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
var stringLenmapvalue uint64 var stringLenmapvalue uint64
for shift := uint(0); ; shift += 7 { for shift := uint(0); ; shift += 7 {
if shift >= 64 { if shift >= 64 {
@ -6344,13 +6320,24 @@ func (m *ObjectMeta) Unmarshal(dAtA []byte) error {
if postStringIndexmapvalue > l { if postStringIndexmapvalue > l {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue]) mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue])
iNdEx = postStringIndexmapvalue iNdEx = postStringIndexmapvalue
m.Annotations[mapkey] = mapvalue
} else { } else {
var mapvalue string iNdEx = entryPreIndex
m.Annotations[mapkey] = mapvalue skippy, err := skipGenerated(dAtA[iNdEx:])
if err != nil {
return err
} }
if skippy < 0 {
return ErrInvalidLengthGenerated
}
if (iNdEx + skippy) > postIndex {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
m.Annotations[mapkey] = mapvalue
iNdEx = postIndex iNdEx = postIndex
case 13: case 13:
if wireType != 2 { if wireType != 2 {

View File

@ -620,8 +620,8 @@ message ObjectMeta {
} }
// OwnerReference contains enough information to let you identify an owning // OwnerReference contains enough information to let you identify an owning
// object. Currently, an owning object must be in the same namespace, so there // object. An owning object must be in the same namespace as the dependent, or
// is no namespace field. // be cluster-scoped, so there is no namespace field.
message OwnerReference { message OwnerReference {
// API version of the referent. // API version of the referent.
optional string apiVersion = 5; optional string apiVersion = 5;

View File

@ -286,8 +286,8 @@ const (
) )
// OwnerReference contains enough information to let you identify an owning // OwnerReference contains enough information to let you identify an owning
// object. Currently, an owning object must be in the same namespace, so there // object. An owning object must be in the same namespace as the dependent, or
// is no namespace field. // be cluster-scoped, so there is no namespace field.
type OwnerReference struct { type OwnerReference struct {
// API version of the referent. // API version of the referent.
APIVersion string `json:"apiVersion" protobuf:"bytes,5,opt,name=apiVersion"` APIVersion string `json:"apiVersion" protobuf:"bytes,5,opt,name=apiVersion"`

View File

@ -240,7 +240,7 @@ func (ObjectMeta) SwaggerDoc() map[string]string {
} }
var map_OwnerReference = map[string]string{ var map_OwnerReference = map[string]string{
"": "OwnerReference contains enough information to let you identify an owning object. Currently, an owning object must be in the same namespace, so there is no namespace field.", "": "OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field.",
"apiVersion": "API version of the referent.", "apiVersion": "API version of the referent.",
"kind": "Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds", "kind": "Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
"name": "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", "name": "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names",

View File

@ -19,4 +19,5 @@ limitations under the License.
// +k8s:defaulter-gen=TypeMeta // +k8s:defaulter-gen=TypeMeta
// +groupName=meta.k8s.io // +groupName=meta.k8s.io
package v1beta1 package v1beta1

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto
// DO NOT EDIT!
/* /*
Package v1beta1 is a generated protocol buffer package. Package v1beta1 is a generated protocol buffer package.
@ -148,24 +147,6 @@ func (m *TableOptions) MarshalTo(dAtA []byte) (int, error) {
return i, nil return i, nil
} }
func encodeFixed64Generated(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
dAtA[offset+4] = uint8(v >> 32)
dAtA[offset+5] = uint8(v >> 40)
dAtA[offset+6] = uint8(v >> 48)
dAtA[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32Generated(dAtA []byte, offset int, v uint32) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 { for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80) dAtA[offset] = uint8(v&0x7f | 0x80)

View File

@ -23,10 +23,10 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/selection" "k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation"
"k8s.io/klog"
) )
// Requirements is AND of all requirements. // Requirements is AND of all requirements.
@ -211,13 +211,13 @@ func (r *Requirement) Matches(ls Labels) bool {
} }
lsValue, err := strconv.ParseInt(ls.Get(r.key), 10, 64) lsValue, err := strconv.ParseInt(ls.Get(r.key), 10, 64)
if err != nil { if err != nil {
glog.V(10).Infof("ParseInt failed for value %+v in label %+v, %+v", ls.Get(r.key), ls, err) klog.V(10).Infof("ParseInt failed for value %+v in label %+v, %+v", ls.Get(r.key), ls, err)
return false return false
} }
// There should be only one strValue in r.strValues, and can be converted to a integer. // There should be only one strValue in r.strValues, and can be converted to a integer.
if len(r.strValues) != 1 { if len(r.strValues) != 1 {
glog.V(10).Infof("Invalid values count %+v of requirement %#v, for 'Gt', 'Lt' operators, exactly one value is required", len(r.strValues), r) klog.V(10).Infof("Invalid values count %+v of requirement %#v, for 'Gt', 'Lt' operators, exactly one value is required", len(r.strValues), r)
return false return false
} }
@ -225,7 +225,7 @@ func (r *Requirement) Matches(ls Labels) bool {
for i := range r.strValues { for i := range r.strValues {
rValue, err = strconv.ParseInt(r.strValues[i], 10, 64) rValue, err = strconv.ParseInt(r.strValues[i], 10, 64)
if err != nil { if err != nil {
glog.V(10).Infof("ParseInt failed for value %+v in requirement %#v, for 'Gt', 'Lt' operators, the value must be an integer", r.strValues[i], r) klog.V(10).Infof("ParseInt failed for value %+v in requirement %#v, for 'Gt', 'Lt' operators, the value must be an integer", r.strValues[i], r)
return false return false
} }
} }

View File

@ -33,7 +33,7 @@ import (
"k8s.io/apimachinery/pkg/util/json" "k8s.io/apimachinery/pkg/util/json"
utilruntime "k8s.io/apimachinery/pkg/util/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"github.com/golang/glog" "k8s.io/klog"
) )
// UnstructuredConverter is an interface for converting between interface{} // UnstructuredConverter is an interface for converting between interface{}
@ -133,10 +133,10 @@ func (c *unstructuredConverter) FromUnstructured(u map[string]interface{}, obj i
newObj := reflect.New(t.Elem()).Interface() newObj := reflect.New(t.Elem()).Interface()
newErr := fromUnstructuredViaJSON(u, newObj) newErr := fromUnstructuredViaJSON(u, newObj)
if (err != nil) != (newErr != nil) { if (err != nil) != (newErr != nil) {
glog.Fatalf("FromUnstructured unexpected error for %v: error: %v", u, err) klog.Fatalf("FromUnstructured unexpected error for %v: error: %v", u, err)
} }
if err == nil && !c.comparison.DeepEqual(obj, newObj) { if err == nil && !c.comparison.DeepEqual(obj, newObj) {
glog.Fatalf("FromUnstructured mismatch\nobj1: %#v\nobj2: %#v", obj, newObj) klog.Fatalf("FromUnstructured mismatch\nobj1: %#v\nobj2: %#v", obj, newObj)
} }
} }
return err return err
@ -424,10 +424,10 @@ func (c *unstructuredConverter) ToUnstructured(obj interface{}) (map[string]inte
newUnstr := map[string]interface{}{} newUnstr := map[string]interface{}{}
newErr := toUnstructuredViaJSON(obj, &newUnstr) newErr := toUnstructuredViaJSON(obj, &newUnstr)
if (err != nil) != (newErr != nil) { if (err != nil) != (newErr != nil) {
glog.Fatalf("ToUnstructured unexpected error for %v: error: %v; newErr: %v", obj, err, newErr) klog.Fatalf("ToUnstructured unexpected error for %v: error: %v; newErr: %v", obj, err, newErr)
} }
if err == nil && !c.comparison.DeepEqual(u, newUnstr) { if err == nil && !c.comparison.DeepEqual(u, newUnstr) {
glog.Fatalf("ToUnstructured mismatch\nobj1: %#v\nobj2: %#v", u, newUnstr) klog.Fatalf("ToUnstructured mismatch\nobj1: %#v\nobj2: %#v", u, newUnstr)
} }
} }
if err != nil { if err != nil {

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/runtime/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/runtime/generated.proto
// DO NOT EDIT!
/* /*
Package runtime is a generated protocol buffer package. Package runtime is a generated protocol buffer package.
@ -158,24 +157,6 @@ func (m *Unknown) MarshalTo(dAtA []byte) (int, error) {
return i, nil return i, nil
} }
func encodeFixed64Generated(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
dAtA[offset+4] = uint8(v >> 32)
dAtA[offset+5] = uint8(v >> 40)
dAtA[offset+6] = uint8(v >> 48)
dAtA[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32Generated(dAtA []byte, offset int, v uint32) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 { for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80) dAtA[offset] = uint8(v&0x7f | 0x80)

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.proto
// DO NOT EDIT!
/* /*
Package schema is a generated protocol buffer package. Package schema is a generated protocol buffer package.

View File

@ -66,7 +66,7 @@ func (gr GroupResource) Empty() bool {
return len(gr.Group) == 0 && len(gr.Resource) == 0 return len(gr.Group) == 0 && len(gr.Resource) == 0
} }
func (gr *GroupResource) String() string { func (gr GroupResource) String() string {
if len(gr.Group) == 0 { if len(gr.Group) == 0 {
return gr.Resource return gr.Resource
} }
@ -111,7 +111,7 @@ func (gvr GroupVersionResource) GroupVersion() GroupVersion {
return GroupVersion{Group: gvr.Group, Version: gvr.Version} return GroupVersion{Group: gvr.Group, Version: gvr.Version}
} }
func (gvr *GroupVersionResource) String() string { func (gvr GroupVersionResource) String() string {
return strings.Join([]string{gvr.Group, "/", gvr.Version, ", Resource=", gvr.Resource}, "") return strings.Join([]string{gvr.Group, "/", gvr.Version, ", Resource=", gvr.Resource}, "")
} }
@ -130,7 +130,7 @@ func (gk GroupKind) WithVersion(version string) GroupVersionKind {
return GroupVersionKind{Group: gk.Group, Version: version, Kind: gk.Kind} return GroupVersionKind{Group: gk.Group, Version: version, Kind: gk.Kind}
} }
func (gk *GroupKind) String() string { func (gk GroupKind) String() string {
if len(gk.Group) == 0 { if len(gk.Group) == 0 {
return gk.Kind return gk.Kind
} }
@ -281,8 +281,8 @@ func bestMatch(kinds []GroupVersionKind, targets []GroupVersionKind) GroupVersio
// ToAPIVersionAndKind is a convenience method for satisfying runtime.Object on types that // ToAPIVersionAndKind is a convenience method for satisfying runtime.Object on types that
// do not use TypeMeta. // do not use TypeMeta.
func (gvk *GroupVersionKind) ToAPIVersionAndKind() (string, string) { func (gvk GroupVersionKind) ToAPIVersionAndKind() (string, string) {
if gvk == nil { if gvk.Empty() {
return "", "" return "", ""
} }
return gvk.GroupVersion().String(), gvk.Kind return gvk.GroupVersion().String(), gvk.Kind

View File

@ -22,9 +22,9 @@ import (
"strconv" "strconv"
"unsafe" "unsafe"
"github.com/ghodss/yaml"
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
"github.com/modern-go/reflect2" "github.com/modern-go/reflect2"
"sigs.k8s.io/yaml"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"

View File

@ -18,6 +18,7 @@ package versioning
import ( import (
"io" "io"
"reflect"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
@ -90,7 +91,16 @@ func (c *codec) Decode(data []byte, defaultGVK *schema.GroupVersionKind, into ru
into = versioned.Last() into = versioned.Last()
} }
obj, gvk, err := c.decoder.Decode(data, defaultGVK, into) // If the into object is unstructured and expresses an opinion about its group/version,
// create a new instance of the type so we always exercise the conversion path (skips short-circuiting on `into == obj`)
decodeInto := into
if into != nil {
if _, ok := into.(runtime.Unstructured); ok && !into.GetObjectKind().GroupVersionKind().GroupVersion().Empty() {
decodeInto = reflect.New(reflect.TypeOf(into).Elem()).Interface().(runtime.Object)
}
}
obj, gvk, err := c.decoder.Decode(data, defaultGVK, decodeInto)
if err != nil { if err != nil {
return nil, gvk, err return nil, gvk, err
} }

View File

@ -136,12 +136,12 @@ func Handshake(req *http.Request, w http.ResponseWriter, serverProtocols []strin
negotiatedProtocol := negotiateProtocol(clientProtocols, serverProtocols) negotiatedProtocol := negotiateProtocol(clientProtocols, serverProtocols)
if len(negotiatedProtocol) == 0 { if len(negotiatedProtocol) == 0 {
w.WriteHeader(http.StatusForbidden)
for i := range serverProtocols { for i := range serverProtocols {
w.Header().Add(HeaderAcceptedProtocolVersions, serverProtocols[i]) w.Header().Add(HeaderAcceptedProtocolVersions, serverProtocols[i])
} }
fmt.Fprintf(w, "unable to upgrade: unable to negotiate protocol: client supports %v, server accepts %v", clientProtocols, serverProtocols) err := fmt.Errorf("unable to upgrade: unable to negotiate protocol: client supports %v, server accepts %v", clientProtocols, serverProtocols)
return "", fmt.Errorf("unable to upgrade: unable to negotiate protocol: client supports %v, server supports %v", clientProtocols, serverProtocols) http.Error(w, err.Error(), http.StatusForbidden)
return "", err
} }
w.Header().Add(HeaderProtocolVersion, negotiatedProtocol) w.Header().Add(HeaderProtocolVersion, negotiatedProtocol)

View File

@ -23,8 +23,8 @@ import (
"time" "time"
"github.com/docker/spdystream" "github.com/docker/spdystream"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/httpstream"
"k8s.io/klog"
) )
// connection maintains state about a spdystream.Connection and its associated // connection maintains state about a spdystream.Connection and its associated
@ -128,7 +128,7 @@ func (c *connection) newSpdyStream(stream *spdystream.Stream) {
err := c.newStreamHandler(stream, replySent) err := c.newStreamHandler(stream, replySent)
rejectStream := (err != nil) rejectStream := (err != nil)
if rejectStream { if rejectStream {
glog.Warningf("Stream rejected: %v", err) klog.Warningf("Stream rejected: %v", err)
stream.Reset() stream.Reset()
return return
} }

View File

@ -67,6 +67,9 @@ type SpdyRoundTripper struct {
// followRedirects indicates if the round tripper should examine responses for redirects and // followRedirects indicates if the round tripper should examine responses for redirects and
// follow them. // follow them.
followRedirects bool followRedirects bool
// requireSameHostRedirects restricts redirect following to only follow redirects to the same host
// as the original request.
requireSameHostRedirects bool
} }
var _ utilnet.TLSClientConfigHolder = &SpdyRoundTripper{} var _ utilnet.TLSClientConfigHolder = &SpdyRoundTripper{}
@ -75,14 +78,18 @@ var _ utilnet.Dialer = &SpdyRoundTripper{}
// NewRoundTripper creates a new SpdyRoundTripper that will use // NewRoundTripper creates a new SpdyRoundTripper that will use
// the specified tlsConfig. // the specified tlsConfig.
func NewRoundTripper(tlsConfig *tls.Config, followRedirects bool) httpstream.UpgradeRoundTripper { func NewRoundTripper(tlsConfig *tls.Config, followRedirects, requireSameHostRedirects bool) httpstream.UpgradeRoundTripper {
return NewSpdyRoundTripper(tlsConfig, followRedirects) return NewSpdyRoundTripper(tlsConfig, followRedirects, requireSameHostRedirects)
} }
// NewSpdyRoundTripper creates a new SpdyRoundTripper that will use // NewSpdyRoundTripper creates a new SpdyRoundTripper that will use
// the specified tlsConfig. This function is mostly meant for unit tests. // the specified tlsConfig. This function is mostly meant for unit tests.
func NewSpdyRoundTripper(tlsConfig *tls.Config, followRedirects bool) *SpdyRoundTripper { func NewSpdyRoundTripper(tlsConfig *tls.Config, followRedirects, requireSameHostRedirects bool) *SpdyRoundTripper {
return &SpdyRoundTripper{tlsConfig: tlsConfig, followRedirects: followRedirects} return &SpdyRoundTripper{
tlsConfig: tlsConfig,
followRedirects: followRedirects,
requireSameHostRedirects: requireSameHostRedirects,
}
} }
// TLSClientConfig implements pkg/util/net.TLSClientConfigHolder for proper TLS checking during // TLSClientConfig implements pkg/util/net.TLSClientConfigHolder for proper TLS checking during
@ -257,7 +264,7 @@ func (s *SpdyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)
) )
if s.followRedirects { if s.followRedirects {
conn, rawResponse, err = utilnet.ConnectWithRedirects(req.Method, req.URL, header, req.Body, s) conn, rawResponse, err = utilnet.ConnectWithRedirects(req.Method, req.URL, header, req.Body, s, s.requireSameHostRedirects)
} else { } else {
clone := utilnet.CloneRequest(req) clone := utilnet.CloneRequest(req)
clone.Header = header clone.Header = header

View File

@ -74,15 +74,15 @@ func (u responseUpgrader) UpgradeResponse(w http.ResponseWriter, req *http.Reque
connectionHeader := strings.ToLower(req.Header.Get(httpstream.HeaderConnection)) connectionHeader := strings.ToLower(req.Header.Get(httpstream.HeaderConnection))
upgradeHeader := strings.ToLower(req.Header.Get(httpstream.HeaderUpgrade)) upgradeHeader := strings.ToLower(req.Header.Get(httpstream.HeaderUpgrade))
if !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) { if !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) {
w.WriteHeader(http.StatusBadRequest) errorMsg := fmt.Sprintf("unable to upgrade: missing upgrade headers in request: %#v", req.Header)
fmt.Fprintf(w, "unable to upgrade: missing upgrade headers in request: %#v", req.Header) http.Error(w, errorMsg, http.StatusBadRequest)
return nil return nil
} }
hijacker, ok := w.(http.Hijacker) hijacker, ok := w.(http.Hijacker)
if !ok { if !ok {
w.WriteHeader(http.StatusInternalServerError) errorMsg := fmt.Sprintf("unable to upgrade: unable to hijack response")
fmt.Fprintf(w, "unable to upgrade: unable to hijack response") http.Error(w, errorMsg, http.StatusInternalServerError)
return nil return nil
} }

View File

@ -14,9 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Code generated by protoc-gen-gogo. // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/util/intstr/generated.proto // source: k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/util/intstr/generated.proto
// DO NOT EDIT!
/* /*
Package intstr is a generated protocol buffer package. Package intstr is a generated protocol buffer package.
@ -81,24 +80,6 @@ func (m *IntOrString) MarshalTo(dAtA []byte) (int, error) {
return i, nil return i, nil
} }
func encodeFixed64Generated(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
dAtA[offset+4] = uint8(v >> 32)
dAtA[offset+5] = uint8(v >> 40)
dAtA[offset+6] = uint8(v >> 48)
dAtA[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32Generated(dAtA []byte, offset int, v uint32) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 { for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80) dAtA[offset] = uint8(v&0x7f | 0x80)

View File

@ -25,8 +25,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/golang/glog"
"github.com/google/gofuzz" "github.com/google/gofuzz"
"k8s.io/klog"
) )
// IntOrString is a type that can hold an int32 or a string. When used in // IntOrString is a type that can hold an int32 or a string. When used in
@ -58,7 +58,7 @@ const (
// TODO: convert to (val int32) // TODO: convert to (val int32)
func FromInt(val int) IntOrString { func FromInt(val int) IntOrString {
if val > math.MaxInt32 || val < math.MinInt32 { if val > math.MaxInt32 || val < math.MinInt32 {
glog.Errorf("value: %d overflows int32\n%s\n", val, debug.Stack()) klog.Errorf("value: %d overflows int32\n%s\n", val, debug.Stack())
} }
return IntOrString{Type: Int, IntVal: int32(val)} return IntOrString{Type: Int, IntVal: int32(val)}
} }

View File

@ -31,8 +31,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/golang/glog"
"golang.org/x/net/http2" "golang.org/x/net/http2"
"k8s.io/klog"
) )
// JoinPreservingTrailingSlash does a path.Join of the specified elements, // JoinPreservingTrailingSlash does a path.Join of the specified elements,
@ -107,10 +107,10 @@ func SetTransportDefaults(t *http.Transport) *http.Transport {
t = SetOldTransportDefaults(t) t = SetOldTransportDefaults(t)
// Allow clients to disable http2 if needed. // Allow clients to disable http2 if needed.
if s := os.Getenv("DISABLE_HTTP2"); len(s) > 0 { if s := os.Getenv("DISABLE_HTTP2"); len(s) > 0 {
glog.Infof("HTTP2 has been explicitly disabled") klog.Infof("HTTP2 has been explicitly disabled")
} else { } else {
if err := http2.ConfigureTransport(t); err != nil { if err := http2.ConfigureTransport(t); err != nil {
glog.Warningf("Transport failed http2 configuration: %v", err) klog.Warningf("Transport failed http2 configuration: %v", err)
} }
} }
return t return t
@ -321,9 +321,10 @@ type Dialer interface {
// ConnectWithRedirects uses dialer to send req, following up to 10 redirects (relative to // ConnectWithRedirects uses dialer to send req, following up to 10 redirects (relative to
// originalLocation). It returns the opened net.Conn and the raw response bytes. // originalLocation). It returns the opened net.Conn and the raw response bytes.
func ConnectWithRedirects(originalMethod string, originalLocation *url.URL, header http.Header, originalBody io.Reader, dialer Dialer) (net.Conn, []byte, error) { // If requireSameHostRedirects is true, only redirects to the same host are permitted.
func ConnectWithRedirects(originalMethod string, originalLocation *url.URL, header http.Header, originalBody io.Reader, dialer Dialer, requireSameHostRedirects bool) (net.Conn, []byte, error) {
const ( const (
maxRedirects = 10 maxRedirects = 9 // Fail on the 10th redirect
maxResponseSize = 16384 // play it safe to allow the potential for lots of / large headers maxResponseSize = 16384 // play it safe to allow the potential for lots of / large headers
) )
@ -367,7 +368,7 @@ redirectLoop:
resp, err := http.ReadResponse(respReader, nil) resp, err := http.ReadResponse(respReader, nil)
if err != nil { if err != nil {
// Unable to read the backend response; let the client handle it. // Unable to read the backend response; let the client handle it.
glog.Warningf("Error reading backend response: %v", err) klog.Warningf("Error reading backend response: %v", err)
break redirectLoop break redirectLoop
} }
@ -387,10 +388,6 @@ redirectLoop:
resp.Body.Close() // not used resp.Body.Close() // not used
// Reset the connection.
intermediateConn.Close()
intermediateConn = nil
// Prepare to follow the redirect. // Prepare to follow the redirect.
redirectStr := resp.Header.Get("Location") redirectStr := resp.Header.Get("Location")
if redirectStr == "" { if redirectStr == "" {
@ -404,6 +401,15 @@ redirectLoop:
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("malformed Location header: %v", err) return nil, nil, fmt.Errorf("malformed Location header: %v", err)
} }
// Only follow redirects to the same host. Otherwise, propagate the redirect response back.
if requireSameHostRedirects && location.Hostname() != originalLocation.Hostname() {
break redirectLoop
}
// Reset the connection.
intermediateConn.Close()
intermediateConn = nil
} }
connToReturn := intermediateConn connToReturn := intermediateConn

View File

@ -26,7 +26,7 @@ import (
"strings" "strings"
"github.com/golang/glog" "k8s.io/klog"
) )
type AddressFamily uint type AddressFamily uint
@ -193,7 +193,7 @@ func isInterfaceUp(intf *net.Interface) bool {
return false return false
} }
if intf.Flags&net.FlagUp != 0 { if intf.Flags&net.FlagUp != 0 {
glog.V(4).Infof("Interface %v is up", intf.Name) klog.V(4).Infof("Interface %v is up", intf.Name)
return true return true
} }
return false return false
@ -208,20 +208,20 @@ func isLoopbackOrPointToPoint(intf *net.Interface) bool {
func getMatchingGlobalIP(addrs []net.Addr, family AddressFamily) (net.IP, error) { func getMatchingGlobalIP(addrs []net.Addr, family AddressFamily) (net.IP, error) {
if len(addrs) > 0 { if len(addrs) > 0 {
for i := range addrs { for i := range addrs {
glog.V(4).Infof("Checking addr %s.", addrs[i].String()) klog.V(4).Infof("Checking addr %s.", addrs[i].String())
ip, _, err := net.ParseCIDR(addrs[i].String()) ip, _, err := net.ParseCIDR(addrs[i].String())
if err != nil { if err != nil {
return nil, err return nil, err
} }
if memberOf(ip, family) { if memberOf(ip, family) {
if ip.IsGlobalUnicast() { if ip.IsGlobalUnicast() {
glog.V(4).Infof("IP found %v", ip) klog.V(4).Infof("IP found %v", ip)
return ip, nil return ip, nil
} else { } else {
glog.V(4).Infof("Non-global unicast address found %v", ip) klog.V(4).Infof("Non-global unicast address found %v", ip)
} }
} else { } else {
glog.V(4).Infof("%v is not an IPv%d address", ip, int(family)) klog.V(4).Infof("%v is not an IPv%d address", ip, int(family))
} }
} }
@ -241,13 +241,13 @@ func getIPFromInterface(intfName string, forFamily AddressFamily, nw networkInte
if err != nil { if err != nil {
return nil, err return nil, err
} }
glog.V(4).Infof("Interface %q has %d addresses :%v.", intfName, len(addrs), addrs) klog.V(4).Infof("Interface %q has %d addresses :%v.", intfName, len(addrs), addrs)
matchingIP, err := getMatchingGlobalIP(addrs, forFamily) matchingIP, err := getMatchingGlobalIP(addrs, forFamily)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if matchingIP != nil { if matchingIP != nil {
glog.V(4).Infof("Found valid IPv%d address %v for interface %q.", int(forFamily), matchingIP, intfName) klog.V(4).Infof("Found valid IPv%d address %v for interface %q.", int(forFamily), matchingIP, intfName)
return matchingIP, nil return matchingIP, nil
} }
} }
@ -275,14 +275,14 @@ func chooseIPFromHostInterfaces(nw networkInterfacer) (net.IP, error) {
return nil, fmt.Errorf("no interfaces found on host.") return nil, fmt.Errorf("no interfaces found on host.")
} }
for _, family := range []AddressFamily{familyIPv4, familyIPv6} { for _, family := range []AddressFamily{familyIPv4, familyIPv6} {
glog.V(4).Infof("Looking for system interface with a global IPv%d address", uint(family)) klog.V(4).Infof("Looking for system interface with a global IPv%d address", uint(family))
for _, intf := range intfs { for _, intf := range intfs {
if !isInterfaceUp(&intf) { if !isInterfaceUp(&intf) {
glog.V(4).Infof("Skipping: down interface %q", intf.Name) klog.V(4).Infof("Skipping: down interface %q", intf.Name)
continue continue
} }
if isLoopbackOrPointToPoint(&intf) { if isLoopbackOrPointToPoint(&intf) {
glog.V(4).Infof("Skipping: LB or P2P interface %q", intf.Name) klog.V(4).Infof("Skipping: LB or P2P interface %q", intf.Name)
continue continue
} }
addrs, err := nw.Addrs(&intf) addrs, err := nw.Addrs(&intf)
@ -290,7 +290,7 @@ func chooseIPFromHostInterfaces(nw networkInterfacer) (net.IP, error) {
return nil, err return nil, err
} }
if len(addrs) == 0 { if len(addrs) == 0 {
glog.V(4).Infof("Skipping: no addresses on interface %q", intf.Name) klog.V(4).Infof("Skipping: no addresses on interface %q", intf.Name)
continue continue
} }
for _, addr := range addrs { for _, addr := range addrs {
@ -299,15 +299,15 @@ func chooseIPFromHostInterfaces(nw networkInterfacer) (net.IP, error) {
return nil, fmt.Errorf("Unable to parse CIDR for interface %q: %s", intf.Name, err) return nil, fmt.Errorf("Unable to parse CIDR for interface %q: %s", intf.Name, err)
} }
if !memberOf(ip, family) { if !memberOf(ip, family) {
glog.V(4).Infof("Skipping: no address family match for %q on interface %q.", ip, intf.Name) klog.V(4).Infof("Skipping: no address family match for %q on interface %q.", ip, intf.Name)
continue continue
} }
// TODO: Decide if should open up to allow IPv6 LLAs in future. // TODO: Decide if should open up to allow IPv6 LLAs in future.
if !ip.IsGlobalUnicast() { if !ip.IsGlobalUnicast() {
glog.V(4).Infof("Skipping: non-global address %q on interface %q.", ip, intf.Name) klog.V(4).Infof("Skipping: non-global address %q on interface %q.", ip, intf.Name)
continue continue
} }
glog.V(4).Infof("Found global unicast address %q on interface %q.", ip, intf.Name) klog.V(4).Infof("Found global unicast address %q on interface %q.", ip, intf.Name)
return ip, nil return ip, nil
} }
} }
@ -381,23 +381,23 @@ func getAllDefaultRoutes() ([]Route, error) {
// an IPv4 IP, and then will look at each IPv6 route for an IPv6 IP. // an IPv4 IP, and then will look at each IPv6 route for an IPv6 IP.
func chooseHostInterfaceFromRoute(routes []Route, nw networkInterfacer) (net.IP, error) { func chooseHostInterfaceFromRoute(routes []Route, nw networkInterfacer) (net.IP, error) {
for _, family := range []AddressFamily{familyIPv4, familyIPv6} { for _, family := range []AddressFamily{familyIPv4, familyIPv6} {
glog.V(4).Infof("Looking for default routes with IPv%d addresses", uint(family)) klog.V(4).Infof("Looking for default routes with IPv%d addresses", uint(family))
for _, route := range routes { for _, route := range routes {
if route.Family != family { if route.Family != family {
continue continue
} }
glog.V(4).Infof("Default route transits interface %q", route.Interface) klog.V(4).Infof("Default route transits interface %q", route.Interface)
finalIP, err := getIPFromInterface(route.Interface, family, nw) finalIP, err := getIPFromInterface(route.Interface, family, nw)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if finalIP != nil { if finalIP != nil {
glog.V(4).Infof("Found active IP %v ", finalIP) klog.V(4).Infof("Found active IP %v ", finalIP)
return finalIP, nil return finalIP, nil
} }
} }
} }
glog.V(4).Infof("No active IP found by looking at default routes") klog.V(4).Infof("No active IP found by looking at default routes")
return nil, fmt.Errorf("unable to select an IP from default routes.") return nil, fmt.Errorf("unable to select an IP from default routes.")
} }

View File

@ -22,7 +22,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/golang/glog" "k8s.io/klog"
) )
var ( var (
@ -63,7 +63,11 @@ func HandleCrash(additionalHandlers ...func(interface{})) {
// logPanic logs the caller tree when a panic occurs. // logPanic logs the caller tree when a panic occurs.
func logPanic(r interface{}) { func logPanic(r interface{}) {
callers := getCallers(r) callers := getCallers(r)
glog.Errorf("Observed a panic: %#v (%v)\n%v", r, r, callers) if _, ok := r.(string); ok {
klog.Errorf("Observed a panic: %s\n%v", r, callers)
} else {
klog.Errorf("Observed a panic: %#v (%v)\n%v", r, r, callers)
}
} }
func getCallers(r interface{}) string { func getCallers(r interface{}) string {
@ -111,7 +115,7 @@ func HandleError(err error) {
// logError prints an error with the call stack of the location it was reported // logError prints an error with the call stack of the location it was reported
func logError(err error) { func logError(err error) {
glog.ErrorDepth(2, err) klog.ErrorDepth(2, err)
} }
type rudimentaryErrorBackoff struct { type rudimentaryErrorBackoff struct {

View File

@ -26,8 +26,8 @@ import (
"strings" "strings"
"unicode" "unicode"
"github.com/ghodss/yaml" "k8s.io/klog"
"github.com/golang/glog" "sigs.k8s.io/yaml"
) )
// ToJSON converts a single YAML document into a JSON document // ToJSON converts a single YAML document into a JSON document
@ -217,11 +217,11 @@ func (d *YAMLOrJSONDecoder) Decode(into interface{}) error {
if d.decoder == nil { if d.decoder == nil {
buffer, origData, isJSON := GuessJSONStream(d.r, d.bufferSize) buffer, origData, isJSON := GuessJSONStream(d.r, d.bufferSize)
if isJSON { if isJSON {
glog.V(4).Infof("decoding stream as JSON") klog.V(4).Infof("decoding stream as JSON")
d.decoder = json.NewDecoder(buffer) d.decoder = json.NewDecoder(buffer)
d.rawData = origData d.rawData = origData
} else { } else {
glog.V(4).Infof("decoding stream as YAML") klog.V(4).Infof("decoding stream as YAML")
d.decoder = NewYAMLToJSONDecoder(buffer) d.decoder = NewYAMLToJSONDecoder(buffer)
} }
} }
@ -230,7 +230,7 @@ func (d *YAMLOrJSONDecoder) Decode(into interface{}) error {
if syntax, ok := err.(*json.SyntaxError); ok { if syntax, ok := err.(*json.SyntaxError); ok {
data, readErr := ioutil.ReadAll(jsonDecoder.Buffered()) data, readErr := ioutil.ReadAll(jsonDecoder.Buffered())
if readErr != nil { if readErr != nil {
glog.V(4).Infof("reading stream failed: %v", readErr) klog.V(4).Infof("reading stream failed: %v", readErr)
} }
js := string(data) js := string(data)

View File

@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// Package version supplies the type for version information collected at build time.
// +k8s:openapi-gen=true // +k8s:openapi-gen=true
// Package version supplies the type for version information collected at build time.
package version // import "k8s.io/apimachinery/pkg/version" package version // import "k8s.io/apimachinery/pkg/version"

View File

@ -20,10 +20,10 @@ import (
"io" "io"
"sync" "sync"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/net" "k8s.io/apimachinery/pkg/util/net"
utilruntime "k8s.io/apimachinery/pkg/util/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/klog"
) )
// Decoder allows StreamWatcher to watch any stream for which a Decoder can be written. // Decoder allows StreamWatcher to watch any stream for which a Decoder can be written.
@ -100,13 +100,13 @@ func (sw *StreamWatcher) receive() {
case io.EOF: case io.EOF:
// watch closed normally // watch closed normally
case io.ErrUnexpectedEOF: case io.ErrUnexpectedEOF:
glog.V(1).Infof("Unexpected EOF during watch stream event decoding: %v", err) klog.V(1).Infof("Unexpected EOF during watch stream event decoding: %v", err)
default: default:
msg := "Unable to decode an event from the watch stream: %v" msg := "Unable to decode an event from the watch stream: %v"
if net.IsProbableEOF(err) { if net.IsProbableEOF(err) {
glog.V(5).Infof(msg, err) klog.V(5).Infof(msg, err)
} else { } else {
glog.Errorf(msg, err) klog.Errorf(msg, err)
} }
} }
return return

View File

@ -20,7 +20,7 @@ import (
"fmt" "fmt"
"sync" "sync"
"github.com/golang/glog" "k8s.io/klog"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
) )
@ -106,7 +106,7 @@ func (f *FakeWatcher) Stop() {
f.Lock() f.Lock()
defer f.Unlock() defer f.Unlock()
if !f.Stopped { if !f.Stopped {
glog.V(4).Infof("Stopping fake watcher.") klog.V(4).Infof("Stopping fake watcher.")
close(f.result) close(f.result)
f.Stopped = true f.Stopped = true
} }
@ -173,7 +173,7 @@ func (f *RaceFreeFakeWatcher) Stop() {
f.Lock() f.Lock()
defer f.Unlock() defer f.Unlock()
if !f.Stopped { if !f.Stopped {
glog.V(4).Infof("Stopping fake watcher.") klog.V(4).Infof("Stopping fake watcher.")
close(f.result) close(f.result)
f.Stopped = true f.Stopped = true
} }

View File

@ -24,7 +24,7 @@ import (
"runtime" "runtime"
"time" "time"
"github.com/golang/glog" "k8s.io/klog"
) )
// StacktracePred returns true if a stacktrace should be logged for this status. // StacktracePred returns true if a stacktrace should be logged for this status.
@ -61,7 +61,7 @@ type passthroughLogger struct{}
// Addf logs info immediately. // Addf logs info immediately.
func (passthroughLogger) Addf(format string, data ...interface{}) { func (passthroughLogger) Addf(format string, data ...interface{}) {
glog.V(2).Info(fmt.Sprintf(format, data...)) klog.V(2).Info(fmt.Sprintf(format, data...))
} }
// DefaultStacktracePred is the default implementation of StacktracePred. // DefaultStacktracePred is the default implementation of StacktracePred.
@ -143,11 +143,11 @@ func (rl *respLogger) Addf(format string, data ...interface{}) {
// Log is intended to be called once at the end of your request handler, via defer // Log is intended to be called once at the end of your request handler, via defer
func (rl *respLogger) Log() { func (rl *respLogger) Log() {
latency := time.Since(rl.startTime) latency := time.Since(rl.startTime)
if glog.V(3) { if klog.V(3) {
if !rl.hijacked { if !rl.hijacked {
glog.InfoDepth(1, fmt.Sprintf("%s %s: (%v) %v%v%v [%s %s]", rl.req.Method, rl.req.RequestURI, latency, rl.status, rl.statusStack, rl.addedInfo, rl.req.UserAgent(), rl.req.RemoteAddr)) klog.InfoDepth(1, fmt.Sprintf("%s %s: (%v) %v%v%v [%s %s]", rl.req.Method, rl.req.RequestURI, latency, rl.status, rl.statusStack, rl.addedInfo, rl.req.UserAgent(), rl.req.RemoteAddr))
} else { } else {
glog.InfoDepth(1, fmt.Sprintf("%s %s: (%v) hijacked [%s %s]", rl.req.Method, rl.req.RequestURI, latency, rl.req.UserAgent(), rl.req.RemoteAddr)) klog.InfoDepth(1, fmt.Sprintf("%s %s: (%v) hijacked [%s %s]", rl.req.Method, rl.req.RequestURI, latency, rl.req.UserAgent(), rl.req.RemoteAddr))
} }
} }
} }
@ -173,8 +173,8 @@ func (rl *respLogger) Write(b []byte) (int, error) {
func (rl *respLogger) Flush() { func (rl *respLogger) Flush() {
if flusher, ok := rl.w.(http.Flusher); ok { if flusher, ok := rl.w.(http.Flusher); ok {
flusher.Flush() flusher.Flush()
} else if glog.V(2) { } else if klog.V(2) {
glog.InfoDepth(1, fmt.Sprintf("Unable to convert %+v into http.Flusher", rl.w)) klog.InfoDepth(1, fmt.Sprintf("Unable to convert %+v into http.Flusher", rl.w))
} }
} }

View File

@ -25,8 +25,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/golang/glog"
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
"k8s.io/klog"
"k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/runtime"
) )
@ -251,7 +251,7 @@ func (conn *Conn) handle(ws *websocket.Conn) {
var data []byte var data []byte
if err := websocket.Message.Receive(ws, &data); err != nil { if err := websocket.Message.Receive(ws, &data); err != nil {
if err != io.EOF { if err != io.EOF {
glog.Errorf("Error on socket receive: %v", err) klog.Errorf("Error on socket receive: %v", err)
} }
break break
} }
@ -264,11 +264,11 @@ func (conn *Conn) handle(ws *websocket.Conn) {
} }
data = data[1:] data = data[1:]
if int(channel) >= len(conn.channels) { if int(channel) >= len(conn.channels) {
glog.V(6).Infof("Frame is targeted for a reader %d that is not valid, possible protocol error", channel) klog.V(6).Infof("Frame is targeted for a reader %d that is not valid, possible protocol error", channel)
continue continue
} }
if _, err := conn.channels[channel].DataFromSocket(data); err != nil { if _, err := conn.channels[channel].DataFromSocket(data); err != nil {
glog.Errorf("Unable to write frame to %d: %v\n%s", channel, err, string(data)) klog.Errorf("Unable to write frame to %d: %v\n%s", channel, err, string(data))
continue continue
} }
} }

24
vendor/k8s.io/client-go/README.md generated vendored
View File

@ -2,7 +2,7 @@
Go clients for talking to a [kubernetes](http://kubernetes.io/) cluster. Go clients for talking to a [kubernetes](http://kubernetes.io/) cluster.
We currently recommend using the v8.0.0 tag. See [INSTALL.md](/INSTALL.md) for We currently recommend using the v9.0.0 tag. See [INSTALL.md](/INSTALL.md) for
detailed installation instructions. `go get k8s.io/client-go/...` works, but detailed installation instructions. `go get k8s.io/client-go/...` works, but
will build `master`, which doesn't handle the dependencies well. will build `master`, which doesn't handle the dependencies well.
@ -91,16 +91,15 @@ We will backport bugfixes--but not new features--into older versions of
#### Compatibility matrix #### Compatibility matrix
| | Kubernetes 1.5 | Kubernetes 1.6 | Kubernetes 1.7 | Kubernetes 1.8 | Kubernetes 1.9 | Kubernetes 1.10 | Kubernetes 1.11 | | | Kubernetes 1.6 | Kubernetes 1.7 | Kubernetes 1.8 | Kubernetes 1.9 | Kubernetes 1.10 | Kubernetes 1.11 | Kubernetes 1.12 |
|---------------------|----------------|----------------|----------------|----------------|----------------|-----------------|-----------------| |---------------------|----------------|----------------|----------------|----------------|-----------------|-----------------|-----------------|
| client-go 1.5 | - | - | - | - | - | - | - | | client-go 3.0 | ✓ | - | +- | +- | +- | +- | +- |
| client-go 2.0 | ✓ | +- | +- | +- | +- | +- | +- | | client-go 4.0 | +- | ✓ | +- | +- | +- | +- | +- |
| client-go 3.0 | +- | ✓ | - | +- | +- | +- | +- | | client-go 5.0 | +- | +- | ✓ | +- | +- | +- | +- |
| client-go 4.0 | +- | +- | ✓ | +- | +- | +- | +- | | client-go 6.0 | +- | +- | +- | ✓ | +- | +- | +- |
| client-go 5.0 | +- | +- | +- | ✓ | +- | +- | +- | | client-go 7.0 | +- | +- | +- | +- | ✓ | +- | +- |
| client-go 6.0 | +- | +- | +- | +- | ✓ | +- | +- | | client-go 8.0 | +- | +- | +- | +- | +- | ✓ | +- |
| client-go 7.0 | +- | +- | +- | +- | +- | ✓ | +- | | client-go 9.0 | +- | +- | +- | +- | +- | +- | ✓ |
| client-go 8.0 | +- | +- | +- | +- | +- | +- | ✓ |
| client-go HEAD | +- | +- | +- | +- | +- | +- | +- | | client-go HEAD | +- | +- | +- | +- | +- | +- | +- |
Key: Key:
@ -128,9 +127,10 @@ between client-go versions.
| client-go 3.0 | Kubernetes main repo, 1.6 branch | = - | | client-go 3.0 | Kubernetes main repo, 1.6 branch | = - |
| client-go 4.0 | Kubernetes main repo, 1.7 branch | = - | | client-go 4.0 | Kubernetes main repo, 1.7 branch | = - |
| client-go 5.0 | Kubernetes main repo, 1.8 branch | = - | | client-go 5.0 | Kubernetes main repo, 1.8 branch | = - |
| client-go 6.0 | Kubernetes main repo, 1.9 branch | | | client-go 6.0 | Kubernetes main repo, 1.9 branch | = - |
| client-go 7.0 | Kubernetes main repo, 1.10 branch | ✓ | | client-go 7.0 | Kubernetes main repo, 1.10 branch | ✓ |
| client-go 8.0 | Kubernetes main repo, 1.11 branch | ✓ | | client-go 8.0 | Kubernetes main repo, 1.11 branch | ✓ |
| client-go 9.0 | Kubernetes main repo, 1.12 branch | ✓ |
| client-go HEAD | Kubernetes main repo, master branch | ✓ | | client-go HEAD | Kubernetes main repo, master branch | ✓ |
Key: Key:

View File

@ -16,4 +16,5 @@ limitations under the License.
// +k8s:deepcopy-gen=package // +k8s:deepcopy-gen=package
// +groupName=client.authentication.k8s.io // +groupName=client.authentication.k8s.io
package clientauthentication // import "k8s.io/client-go/pkg/apis/clientauthentication" package clientauthentication // import "k8s.io/client-go/pkg/apis/clientauthentication"

View File

@ -20,4 +20,5 @@ limitations under the License.
// +k8s:defaulter-gen=TypeMeta // +k8s:defaulter-gen=TypeMeta
// +groupName=client.authentication.k8s.io // +groupName=client.authentication.k8s.io
package v1alpha1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1" package v1alpha1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1"

View File

@ -20,4 +20,5 @@ limitations under the License.
// +k8s:defaulter-gen=TypeMeta // +k8s:defaulter-gen=TypeMeta
// +groupName=client.authentication.k8s.io // +groupName=client.authentication.k8s.io
package v1beta1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1" package v1beta1 // import "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1"

View File

@ -14,7 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
// +k8s:openapi-gen=true
// Package version supplies version information collected at build time to // Package version supplies version information collected at build time to
// kubernetes components. // kubernetes components.
// +k8s:openapi-gen=true
package version // import "k8s.io/client-go/pkg/version" package version // import "k8s.io/client-go/pkg/version"

View File

@ -31,7 +31,6 @@ import (
"sync" "sync"
"time" "time"
"github.com/golang/glog"
"golang.org/x/crypto/ssh/terminal" "golang.org/x/crypto/ssh/terminal"
"k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
@ -44,6 +43,7 @@ import (
"k8s.io/client-go/tools/clientcmd/api" "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/transport" "k8s.io/client-go/transport"
"k8s.io/client-go/util/connrotation" "k8s.io/client-go/util/connrotation"
"k8s.io/klog"
) )
const execInfoEnv = "KUBERNETES_EXEC_INFO" const execInfoEnv = "KUBERNETES_EXEC_INFO"
@ -228,7 +228,7 @@ func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
Code: int32(res.StatusCode), Code: int32(res.StatusCode),
} }
if err := r.a.maybeRefreshCreds(creds, resp); err != nil { if err := r.a.maybeRefreshCreds(creds, resp); err != nil {
glog.Errorf("refreshing credentials: %v", err) klog.Errorf("refreshing credentials: %v", err)
} }
} }
return res, nil return res, nil

View File

@ -29,7 +29,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/golang/glog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
@ -37,6 +36,7 @@ import (
clientcmdapi "k8s.io/client-go/tools/clientcmd/api" clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
certutil "k8s.io/client-go/util/cert" certutil "k8s.io/client-go/util/cert"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog"
) )
const ( const (
@ -322,7 +322,7 @@ func InClusterConfig() (*Config, error) {
return nil, ErrNotInCluster return nil, ErrNotInCluster
} }
ts := newCachedPathTokenSource(tokenFile) ts := NewCachedFileTokenSource(tokenFile)
if _, err := ts.Token(); err != nil { if _, err := ts.Token(); err != nil {
return nil, err return nil, err
@ -331,7 +331,7 @@ func InClusterConfig() (*Config, error) {
tlsClientConfig := TLSClientConfig{} tlsClientConfig := TLSClientConfig{}
if _, err := certutil.NewPool(rootCAFile); err != nil { if _, err := certutil.NewPool(rootCAFile); err != nil {
glog.Errorf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err) klog.Errorf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err)
} else { } else {
tlsClientConfig.CAFile = rootCAFile tlsClientConfig.CAFile = rootCAFile
} }

View File

@ -21,7 +21,7 @@ import (
"net/http" "net/http"
"sync" "sync"
"github.com/golang/glog" "k8s.io/klog"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api" clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
) )
@ -57,7 +57,7 @@ func RegisterAuthProviderPlugin(name string, plugin Factory) error {
if _, found := plugins[name]; found { if _, found := plugins[name]; found {
return fmt.Errorf("Auth Provider Plugin %q was registered twice", name) return fmt.Errorf("Auth Provider Plugin %q was registered twice", name)
} }
glog.V(4).Infof("Registered Auth Provider Plugin %q", name) klog.V(4).Infof("Registered Auth Provider Plugin %q", name)
plugins[name] = plugin plugins[name] = plugin
return nil return nil
} }

View File

@ -32,7 +32,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/golang/glog"
"golang.org/x/net/http2" "golang.org/x/net/http2"
"k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -44,6 +43,7 @@ import (
restclientwatch "k8s.io/client-go/rest/watch" restclientwatch "k8s.io/client-go/rest/watch"
"k8s.io/client-go/tools/metrics" "k8s.io/client-go/tools/metrics"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog"
) )
var ( var (
@ -114,7 +114,7 @@ type Request struct {
// NewRequest creates a new request helper object for accessing runtime.Objects on a server. // NewRequest creates a new request helper object for accessing runtime.Objects on a server.
func NewRequest(client HTTPClient, verb string, baseURL *url.URL, versionedAPIPath string, content ContentConfig, serializers Serializers, backoff BackoffManager, throttle flowcontrol.RateLimiter, timeout time.Duration) *Request { func NewRequest(client HTTPClient, verb string, baseURL *url.URL, versionedAPIPath string, content ContentConfig, serializers Serializers, backoff BackoffManager, throttle flowcontrol.RateLimiter, timeout time.Duration) *Request {
if backoff == nil { if backoff == nil {
glog.V(2).Infof("Not implementing request backoff strategy.") klog.V(2).Infof("Not implementing request backoff strategy.")
backoff = &NoBackoff{} backoff = &NoBackoff{}
} }
@ -527,7 +527,7 @@ func (r *Request) tryThrottle() {
r.throttle.Accept() r.throttle.Accept()
} }
if latency := time.Since(now); latency > longThrottleLatency { if latency := time.Since(now); latency > longThrottleLatency {
glog.V(4).Infof("Throttling request took %v, request: %s:%s", latency, r.verb, r.URL().String()) klog.V(4).Infof("Throttling request took %v, request: %s:%s", latency, r.verb, r.URL().String())
} }
} }
@ -683,7 +683,7 @@ func (r *Request) request(fn func(*http.Request, *http.Response)) error {
}() }()
if r.err != nil { if r.err != nil {
glog.V(4).Infof("Error in request: %v", r.err) klog.V(4).Infof("Error in request: %v", r.err)
return r.err return r.err
} }
@ -770,13 +770,13 @@ func (r *Request) request(fn func(*http.Request, *http.Response)) error {
if seeker, ok := r.body.(io.Seeker); ok && r.body != nil { if seeker, ok := r.body.(io.Seeker); ok && r.body != nil {
_, err := seeker.Seek(0, 0) _, err := seeker.Seek(0, 0)
if err != nil { if err != nil {
glog.V(4).Infof("Could not retry request, can't Seek() back to beginning of body for %T", r.body) klog.V(4).Infof("Could not retry request, can't Seek() back to beginning of body for %T", r.body)
fn(req, resp) fn(req, resp)
return true return true
} }
} }
glog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url) klog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url)
r.backoffMgr.Sleep(time.Duration(seconds) * time.Second) r.backoffMgr.Sleep(time.Duration(seconds) * time.Second)
return false return false
} }
@ -844,13 +844,13 @@ func (r *Request) transformResponse(resp *http.Response, req *http.Request) Resu
// 2. Apiserver sends back the headers and then part of the body // 2. Apiserver sends back the headers and then part of the body
// 3. Apiserver closes connection. // 3. Apiserver closes connection.
// 4. client-go should catch this and return an error. // 4. client-go should catch this and return an error.
glog.V(2).Infof("Stream error %#v when reading response body, may be caused by closed connection.", err) klog.V(2).Infof("Stream error %#v when reading response body, may be caused by closed connection.", err)
streamErr := fmt.Errorf("Stream error %#v when reading response body, may be caused by closed connection. Please retry.", err) streamErr := fmt.Errorf("Stream error %#v when reading response body, may be caused by closed connection. Please retry.", err)
return Result{ return Result{
err: streamErr, err: streamErr,
} }
default: default:
glog.Errorf("Unexpected error when reading response body: %#v", err) klog.Errorf("Unexpected error when reading response body: %#v", err)
unexpectedErr := fmt.Errorf("Unexpected error %#v when reading response body. Please retry.", err) unexpectedErr := fmt.Errorf("Unexpected error %#v when reading response body. Please retry.", err)
return Result{ return Result{
err: unexpectedErr, err: unexpectedErr,
@ -914,11 +914,11 @@ func (r *Request) transformResponse(resp *http.Response, req *http.Request) Resu
func truncateBody(body string) string { func truncateBody(body string) string {
max := 0 max := 0
switch { switch {
case bool(glog.V(10)): case bool(klog.V(10)):
return body return body
case bool(glog.V(9)): case bool(klog.V(9)):
max = 10240 max = 10240
case bool(glog.V(8)): case bool(klog.V(8)):
max = 1024 max = 1024
} }
@ -933,13 +933,13 @@ func truncateBody(body string) string {
// allocating a new string for the body output unless necessary. Uses a simple heuristic to determine // allocating a new string for the body output unless necessary. Uses a simple heuristic to determine
// whether the body is printable. // whether the body is printable.
func glogBody(prefix string, body []byte) { func glogBody(prefix string, body []byte) {
if glog.V(8) { if klog.V(8) {
if bytes.IndexFunc(body, func(r rune) bool { if bytes.IndexFunc(body, func(r rune) bool {
return r < 0x0a return r < 0x0a
}) != -1 { }) != -1 {
glog.Infof("%s:\n%s", prefix, truncateBody(hex.Dump(body))) klog.Infof("%s:\n%s", prefix, truncateBody(hex.Dump(body)))
} else { } else {
glog.Infof("%s: %s", prefix, truncateBody(string(body))) klog.Infof("%s: %s", prefix, truncateBody(string(body)))
} }
} }
} }
@ -1141,7 +1141,7 @@ func (r Result) Error() error {
// to be backwards compatible with old servers that do not return a version, default to "v1" // to be backwards compatible with old servers that do not return a version, default to "v1"
out, _, err := r.decoder.Decode(r.body, &schema.GroupVersionKind{Version: "v1"}, nil) out, _, err := r.decoder.Decode(r.body, &schema.GroupVersionKind{Version: "v1"}, nil)
if err != nil { if err != nil {
glog.V(5).Infof("body was not decodable (unable to check for Status): %v", err) klog.V(5).Infof("body was not decodable (unable to check for Status): %v", err)
return r.err return r.err
} }
switch t := out.(type) { switch t := out.(type) {

View File

@ -24,8 +24,8 @@ import (
"sync" "sync"
"time" "time"
"github.com/golang/glog"
"golang.org/x/oauth2" "golang.org/x/oauth2"
"k8s.io/klog"
) )
// TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens // TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens
@ -42,7 +42,9 @@ func TokenSourceWrapTransport(ts oauth2.TokenSource) func(http.RoundTripper) htt
} }
} }
func newCachedPathTokenSource(path string) oauth2.TokenSource { // NewCachedFileTokenSource returns a oauth2.TokenSource reads a token from a
// file at a specified path and periodically reloads it.
func NewCachedFileTokenSource(path string) oauth2.TokenSource {
return &cachingTokenSource{ return &cachingTokenSource{
now: time.Now, now: time.Now,
leeway: 1 * time.Minute, leeway: 1 * time.Minute,
@ -129,7 +131,7 @@ func (ts *cachingTokenSource) Token() (*oauth2.Token, error) {
if ts.tok == nil { if ts.tok == nil {
return nil, err return nil, err
} }
glog.Errorf("Unable to rotate token: %v", err) klog.Errorf("Unable to rotate token: %v", err)
return ts.tok, nil return ts.tok, nil
} }

View File

@ -20,9 +20,9 @@ import (
"net/url" "net/url"
"time" "time"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog"
) )
// Set of resp. Codes that we backoff for. // Set of resp. Codes that we backoff for.
@ -64,7 +64,7 @@ func (n *NoBackoff) Sleep(d time.Duration) {
// Disable makes the backoff trivial, i.e., sets it to zero. This might be used // Disable makes the backoff trivial, i.e., sets it to zero. This might be used
// by tests which want to run 1000s of mock requests without slowing down. // by tests which want to run 1000s of mock requests without slowing down.
func (b *URLBackoff) Disable() { func (b *URLBackoff) Disable() {
glog.V(4).Infof("Disabling backoff strategy") klog.V(4).Infof("Disabling backoff strategy")
b.Backoff = flowcontrol.NewBackOff(0*time.Second, 0*time.Second) b.Backoff = flowcontrol.NewBackOff(0*time.Second, 0*time.Second)
} }
@ -76,7 +76,7 @@ func (b *URLBackoff) baseUrlKey(rawurl *url.URL) string {
// in the future. // in the future.
host, err := url.Parse(rawurl.String()) host, err := url.Parse(rawurl.String())
if err != nil { if err != nil {
glog.V(4).Infof("Error extracting url: %v", rawurl) klog.V(4).Infof("Error extracting url: %v", rawurl)
panic("bad url!") panic("bad url!")
} }
return host.Host return host.Host
@ -89,7 +89,7 @@ func (b *URLBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode i
b.Backoff.Next(b.baseUrlKey(actualUrl), b.Backoff.Clock.Now()) b.Backoff.Next(b.baseUrlKey(actualUrl), b.Backoff.Clock.Now())
return return
} else if responseCode >= 300 || err != nil { } else if responseCode >= 300 || err != nil {
glog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err) klog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err)
} }
//If we got this far, there is no backoff required for this URL anymore. //If we got this far, there is no backoff required for this URL anymore.

View File

@ -15,4 +15,5 @@ limitations under the License.
*/ */
// +k8s:deepcopy-gen=package // +k8s:deepcopy-gen=package
package api package api

41
vendor/k8s.io/client-go/tools/remotecommand/reader.go generated vendored Normal file
View File

@ -0,0 +1,41 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package remotecommand
import (
"io"
)
// readerWrapper delegates to an io.Reader so that only the io.Reader interface is implemented,
// to keep io.Copy from doing things we don't want when copying from the reader to the data stream.
//
// If the Stdin io.Reader provided to remotecommand implements a WriteTo function (like bytes.Buffer does[1]),
// io.Copy calls that method[2] to attempt to write the entire buffer to the stream in one call.
// That results in an oversized call to spdystream.Stream#Write [3],
// which results in a single oversized data frame[4] that is too large.
//
// [1] https://golang.org/pkg/bytes/#Buffer.WriteTo
// [2] https://golang.org/pkg/io/#Copy
// [3] https://github.com/kubernetes/kubernetes/blob/90295640ef87db9daa0144c5617afe889e7992b2/vendor/github.com/docker/spdystream/stream.go#L66-L73
// [4] https://github.com/kubernetes/kubernetes/blob/90295640ef87db9daa0144c5617afe889e7992b2/vendor/github.com/docker/spdystream/spdy/write.go#L302-L304
type readerWrapper struct {
reader io.Reader
}
func (r readerWrapper) Read(p []byte) (int, error) {
return r.reader.Read(p)
}

View File

@ -22,7 +22,7 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"github.com/golang/glog" "k8s.io/klog"
"k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/httpstream"
"k8s.io/apimachinery/pkg/util/remotecommand" "k8s.io/apimachinery/pkg/util/remotecommand"
@ -132,7 +132,7 @@ func (e *streamExecutor) Stream(options StreamOptions) error {
case remotecommand.StreamProtocolV2Name: case remotecommand.StreamProtocolV2Name:
streamer = newStreamProtocolV2(options) streamer = newStreamProtocolV2(options)
case "": case "":
glog.V(4).Infof("The server did not negotiate a streaming protocol version. Falling back to %s", remotecommand.StreamProtocolV1Name) klog.V(4).Infof("The server did not negotiate a streaming protocol version. Falling back to %s", remotecommand.StreamProtocolV1Name)
fallthrough fallthrough
case remotecommand.StreamProtocolV1Name: case remotecommand.StreamProtocolV1Name:
streamer = newStreamProtocolV1(options) streamer = newStreamProtocolV1(options)

View File

@ -22,9 +22,9 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"github.com/golang/glog"
"k8s.io/api/core/v1" "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/httpstream"
"k8s.io/klog"
) )
// streamProtocolV1 implements the first version of the streaming exec & attach // streamProtocolV1 implements the first version of the streaming exec & attach
@ -53,10 +53,10 @@ func (p *streamProtocolV1) stream(conn streamCreator) error {
errorChan := make(chan error) errorChan := make(chan error)
cp := func(s string, dst io.Writer, src io.Reader) { cp := func(s string, dst io.Writer, src io.Reader) {
glog.V(6).Infof("Copying %s", s) klog.V(6).Infof("Copying %s", s)
defer glog.V(6).Infof("Done copying %s", s) defer klog.V(6).Infof("Done copying %s", s)
if _, err := io.Copy(dst, src); err != nil && err != io.EOF { if _, err := io.Copy(dst, src); err != nil && err != io.EOF {
glog.Errorf("Error copying %s: %v", s, err) klog.Errorf("Error copying %s: %v", s, err)
} }
if s == v1.StreamTypeStdout || s == v1.StreamTypeStderr { if s == v1.StreamTypeStdout || s == v1.StreamTypeStderr {
doneChan <- struct{}{} doneChan <- struct{}{}
@ -127,7 +127,7 @@ func (p *streamProtocolV1) stream(conn streamCreator) error {
// because stdin is not closed until the process exits. If we try to call // because stdin is not closed until the process exits. If we try to call
// stdin.Close(), it returns no error but doesn't unblock the copy. It will // stdin.Close(), it returns no error but doesn't unblock the copy. It will
// exit when the process exits, instead. // exit when the process exits, instead.
go cp(v1.StreamTypeStdin, p.remoteStdin, p.Stdin) go cp(v1.StreamTypeStdin, p.remoteStdin, readerWrapper{p.Stdin})
} }
waitCount := 0 waitCount := 0

View File

@ -101,7 +101,7 @@ func (p *streamProtocolV2) copyStdin() {
// the executed command will remain running. // the executed command will remain running.
defer once.Do(func() { p.remoteStdin.Close() }) defer once.Do(func() { p.remoteStdin.Close() })
if _, err := io.Copy(p.remoteStdin, p.Stdin); err != nil { if _, err := io.Copy(p.remoteStdin, readerWrapper{p.Stdin}); err != nil {
runtime.HandleError(err) runtime.HandleError(err)
} }
}() }()

View File

@ -22,7 +22,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/golang/glog" "k8s.io/klog"
utilnet "k8s.io/apimachinery/pkg/util/net" utilnet "k8s.io/apimachinery/pkg/util/net"
) )
@ -62,13 +62,13 @@ func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTrip
// DebugWrappers wraps a round tripper and logs based on the current log level. // DebugWrappers wraps a round tripper and logs based on the current log level.
func DebugWrappers(rt http.RoundTripper) http.RoundTripper { func DebugWrappers(rt http.RoundTripper) http.RoundTripper {
switch { switch {
case bool(glog.V(9)): case bool(klog.V(9)):
rt = newDebuggingRoundTripper(rt, debugCurlCommand, debugURLTiming, debugResponseHeaders) rt = newDebuggingRoundTripper(rt, debugCurlCommand, debugURLTiming, debugResponseHeaders)
case bool(glog.V(8)): case bool(klog.V(8)):
rt = newDebuggingRoundTripper(rt, debugJustURL, debugRequestHeaders, debugResponseStatus, debugResponseHeaders) rt = newDebuggingRoundTripper(rt, debugJustURL, debugRequestHeaders, debugResponseStatus, debugResponseHeaders)
case bool(glog.V(7)): case bool(klog.V(7)):
rt = newDebuggingRoundTripper(rt, debugJustURL, debugRequestHeaders, debugResponseStatus) rt = newDebuggingRoundTripper(rt, debugJustURL, debugRequestHeaders, debugResponseStatus)
case bool(glog.V(6)): case bool(klog.V(6)):
rt = newDebuggingRoundTripper(rt, debugURLTiming) rt = newDebuggingRoundTripper(rt, debugURLTiming)
} }
@ -138,7 +138,7 @@ func (rt *authProxyRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.rt.(requestCanceler); ok { if canceler, ok := rt.rt.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.rt) klog.Errorf("CancelRequest not implemented by %T", rt.rt)
} }
} }
@ -166,7 +166,7 @@ func (rt *userAgentRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.rt.(requestCanceler); ok { if canceler, ok := rt.rt.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.rt) klog.Errorf("CancelRequest not implemented by %T", rt.rt)
} }
} }
@ -197,7 +197,7 @@ func (rt *basicAuthRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.rt.(requestCanceler); ok { if canceler, ok := rt.rt.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.rt) klog.Errorf("CancelRequest not implemented by %T", rt.rt)
} }
} }
@ -257,7 +257,7 @@ func (rt *impersonatingRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.delegate.(requestCanceler); ok { if canceler, ok := rt.delegate.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.delegate) klog.Errorf("CancelRequest not implemented by %T", rt.delegate)
} }
} }
@ -288,7 +288,7 @@ func (rt *bearerAuthRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.rt.(requestCanceler); ok { if canceler, ok := rt.rt.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.rt) klog.Errorf("CancelRequest not implemented by %T", rt.rt)
} }
} }
@ -372,7 +372,7 @@ func (rt *debuggingRoundTripper) CancelRequest(req *http.Request) {
if canceler, ok := rt.delegatedRoundTripper.(requestCanceler); ok { if canceler, ok := rt.delegatedRoundTripper.(requestCanceler); ok {
canceler.CancelRequest(req) canceler.CancelRequest(req)
} else { } else {
glog.Errorf("CancelRequest not implemented by %T", rt.delegatedRoundTripper) klog.Errorf("CancelRequest not implemented by %T", rt.delegatedRoundTripper)
} }
} }
@ -380,17 +380,17 @@ func (rt *debuggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, e
reqInfo := newRequestInfo(req) reqInfo := newRequestInfo(req)
if rt.levels[debugJustURL] { if rt.levels[debugJustURL] {
glog.Infof("%s %s", reqInfo.RequestVerb, reqInfo.RequestURL) klog.Infof("%s %s", reqInfo.RequestVerb, reqInfo.RequestURL)
} }
if rt.levels[debugCurlCommand] { if rt.levels[debugCurlCommand] {
glog.Infof("%s", reqInfo.toCurl()) klog.Infof("%s", reqInfo.toCurl())
} }
if rt.levels[debugRequestHeaders] { if rt.levels[debugRequestHeaders] {
glog.Infof("Request Headers:") klog.Infof("Request Headers:")
for key, values := range reqInfo.RequestHeaders { for key, values := range reqInfo.RequestHeaders {
for _, value := range values { for _, value := range values {
glog.Infof(" %s: %s", key, value) klog.Infof(" %s: %s", key, value)
} }
} }
} }
@ -402,16 +402,16 @@ func (rt *debuggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, e
reqInfo.complete(response, err) reqInfo.complete(response, err)
if rt.levels[debugURLTiming] { if rt.levels[debugURLTiming] {
glog.Infof("%s %s %s in %d milliseconds", reqInfo.RequestVerb, reqInfo.RequestURL, reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond)) klog.Infof("%s %s %s in %d milliseconds", reqInfo.RequestVerb, reqInfo.RequestURL, reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond))
} }
if rt.levels[debugResponseStatus] { if rt.levels[debugResponseStatus] {
glog.Infof("Response Status: %s in %d milliseconds", reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond)) klog.Infof("Response Status: %s in %d milliseconds", reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond))
} }
if rt.levels[debugResponseHeaders] { if rt.levels[debugResponseHeaders] {
glog.Infof("Response Headers:") klog.Infof("Response Headers:")
for key, values := range reqInfo.ResponseHeaders { for key, values := range reqInfo.ResponseHeaders {
for _, value := range values { for _, value := range values {
glog.Infof(" %s: %s", key, value) klog.Infof(" %s: %s", key, value)
} }
} }
} }

View File

@ -38,7 +38,7 @@ func RoundTripperFor(config *restclient.Config) (http.RoundTripper, Upgrader, er
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
upgradeRoundTripper := spdy.NewRoundTripper(tlsConfig, true) upgradeRoundTripper := spdy.NewRoundTripper(tlsConfig, true, false)
wrapper, err := restclient.HTTPWrappersForConfig(config, upgradeRoundTripper) wrapper, err := restclient.HTTPWrappersForConfig(config, upgradeRoundTripper)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err

View File

@ -18,6 +18,7 @@ package cert
import ( import (
"bytes" "bytes"
"crypto"
"crypto/ecdsa" "crypto/ecdsa"
"crypto/elliptic" "crypto/elliptic"
"crypto/rand" "crypto/rand"
@ -64,7 +65,7 @@ func NewPrivateKey() (*rsa.PrivateKey, error) {
} }
// NewSelfSignedCACert creates a CA certificate // NewSelfSignedCACert creates a CA certificate
func NewSelfSignedCACert(cfg Config, key *rsa.PrivateKey) (*x509.Certificate, error) { func NewSelfSignedCACert(cfg Config, key crypto.Signer) (*x509.Certificate, error) {
now := time.Now() now := time.Now()
tmpl := x509.Certificate{ tmpl := x509.Certificate{
SerialNumber: new(big.Int).SetInt64(0), SerialNumber: new(big.Int).SetInt64(0),
@ -87,7 +88,7 @@ func NewSelfSignedCACert(cfg Config, key *rsa.PrivateKey) (*x509.Certificate, er
} }
// NewSignedCert creates a signed certificate using the given CA certificate and key // NewSignedCert creates a signed certificate using the given CA certificate and key
func NewSignedCert(cfg Config, key *rsa.PrivateKey, caCert *x509.Certificate, caKey *rsa.PrivateKey) (*x509.Certificate, error) { func NewSignedCert(cfg Config, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer) (*x509.Certificate, error) {
serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64))
if err != nil { if err != nil {
return nil, err return nil, err
@ -259,34 +260,6 @@ func GenerateSelfSignedCertKeyWithFixtures(host string, alternateIPs []net.IP, a
return certBuffer.Bytes(), keyBuffer.Bytes(), nil return certBuffer.Bytes(), keyBuffer.Bytes(), nil
} }
// FormatBytesCert receives byte array certificate and formats in human-readable format
func FormatBytesCert(cert []byte) (string, error) {
block, _ := pem.Decode(cert)
c, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return "", fmt.Errorf("failed to parse certificate [%v]", err)
}
return FormatCert(c), nil
}
// FormatCert receives certificate and formats in human-readable format
func FormatCert(c *x509.Certificate) string {
var ips []string
for _, ip := range c.IPAddresses {
ips = append(ips, ip.String())
}
altNames := append(ips, c.DNSNames...)
res := fmt.Sprintf(
"Issuer: CN=%s | Subject: CN=%s | CA: %t\n",
c.Issuer.CommonName, c.Subject.CommonName, c.IsCA,
)
res += fmt.Sprintf("Not before: %s Not After: %s", c.NotBefore, c.NotAfter)
if len(altNames) > 0 {
res += fmt.Sprintf("\nAlternate Names: %v", altNames)
}
return res
}
func ipsToStrings(ips []net.IP) []string { func ipsToStrings(ips []net.IP) []string {
ss := make([]string, 0, len(ips)) ss := make([]string, 0, len(ips))
for _, ip := range ips { for _, ip := range ips {

View File

@ -1,3 +1,10 @@
klog
====
klog is a permanant fork of https://github.com/golang/glog. original README from glog is below
----
glog glog
==== ====
@ -5,7 +12,7 @@ Leveled execution logs for Go.
This is an efficient pure Go implementation of leveled logs in the This is an efficient pure Go implementation of leveled logs in the
manner of the open source C++ package manner of the open source C++ package
http://code.google.com/p/google-glog https://github.com/google/glog
By binding methods to booleans it is possible to use the log package By binding methods to booleans it is possible to use the log package
without paying the expense of evaluating the arguments to the log. without paying the expense of evaluating the arguments to the log.

View File

@ -14,7 +14,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// Package glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. // Package klog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup.
// It provides functions Info, Warning, Error, Fatal, plus formatting variants such as // It provides functions Info, Warning, Error, Fatal, plus formatting variants such as
// Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags. // Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags.
// //
@ -68,7 +68,7 @@
// -vmodule=gopher*=3 // -vmodule=gopher*=3
// sets the V level to 3 in all Go files whose names begin "gopher". // sets the V level to 3 in all Go files whose names begin "gopher".
// //
package glog package klog
import ( import (
"bufio" "bufio"
@ -396,13 +396,6 @@ type flushSyncWriter interface {
} }
func init() { func init() {
flag.BoolVar(&logging.toStderr, "logtostderr", false, "log to standard error instead of files")
flag.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "log to standard error as well as files")
flag.Var(&logging.verbosity, "v", "log level for V logs")
flag.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
flag.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
flag.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
// Default stderrThreshold is ERROR. // Default stderrThreshold is ERROR.
logging.stderrThreshold = errorLog logging.stderrThreshold = errorLog
@ -410,6 +403,22 @@ func init() {
go logging.flushDaemon() go logging.flushDaemon()
} }
// InitFlags is for explicitly initializing the flags
func InitFlags(flagset *flag.FlagSet) {
if flagset == nil {
flagset = flag.CommandLine
}
flagset.StringVar(&logging.logDir, "log_dir", "", "If non-empty, write log files in this directory")
flagset.StringVar(&logging.logFile, "log_file", "", "If non-empty, use this log file")
flagset.BoolVar(&logging.toStderr, "logtostderr", false, "log to standard error instead of files")
flagset.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "log to standard error as well as files")
flagset.Var(&logging.verbosity, "v", "log level for V logs")
flagset.BoolVar(&logging.skipHeaders, "skip_headers", false, "If true, avoid header prefixes in the log messages")
flagset.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
flagset.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
flagset.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
}
// Flush flushes all pending log I/O. // Flush flushes all pending log I/O.
func Flush() { func Flush() {
logging.lockAndFlushAll() logging.lockAndFlushAll()
@ -453,6 +462,17 @@ type loggingT struct {
// safely using atomic.LoadInt32. // safely using atomic.LoadInt32.
vmodule moduleSpec // The state of the -vmodule flag. vmodule moduleSpec // The state of the -vmodule flag.
verbosity Level // V logging level, the value of the -v flag/ verbosity Level // V logging level, the value of the -v flag/
// If non-empty, overrides the choice of directory in which to write logs.
// See createLogDirs for the full list of possible destinations.
logDir string
// If non-empty, specifies the path of the file to write logs. mutually exclusive
// with the log-dir option.
logFile string
// If true, do not add the prefix headers, useful when used with SetOutput
skipHeaders bool
} }
// buffer holds a byte Buffer for reuse. The zero value is ready for use. // buffer holds a byte Buffer for reuse. The zero value is ready for use.
@ -556,6 +576,9 @@ func (l *loggingT) formatHeader(s severity, file string, line int) *buffer {
s = infoLog // for safety. s = infoLog // for safety.
} }
buf := l.getBuffer() buf := l.getBuffer()
if l.skipHeaders {
return buf
}
// Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand.
// It's worth about 3X. Fprintf is hard. // It's worth about 3X. Fprintf is hard.
@ -667,6 +690,45 @@ func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToSt
l.output(s, buf, file, line, alsoToStderr) l.output(s, buf, file, line, alsoToStderr)
} }
// redirectBuffer is used to set an alternate destination for the logs
type redirectBuffer struct {
w io.Writer
}
func (rb *redirectBuffer) Sync() error {
return nil
}
func (rb *redirectBuffer) Flush() error {
return nil
}
func (rb *redirectBuffer) Write(bytes []byte) (n int, err error) {
return rb.w.Write(bytes)
}
// SetOutput sets the output destination for all severities
func SetOutput(w io.Writer) {
for s := fatalLog; s >= infoLog; s-- {
rb := &redirectBuffer{
w: w,
}
logging.file[s] = rb
}
}
// SetOutputBySeverity sets the output destination for specific severity
func SetOutputBySeverity(name string, w io.Writer) {
sev, ok := severityByName(name)
if !ok {
panic(fmt.Sprintf("SetOutputBySeverity(%q): unrecognized severity name", name))
}
rb := &redirectBuffer{
w: w,
}
logging.file[sev] = rb
}
// output writes the data to the log files and releases the buffer. // output writes the data to the log files and releases the buffer.
func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) { func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) {
l.mu.Lock() l.mu.Lock()
@ -876,7 +938,7 @@ const flushInterval = 30 * time.Second
// flushDaemon periodically flushes the log file buffers. // flushDaemon periodically flushes the log file buffers.
func (l *loggingT) flushDaemon() { func (l *loggingT) flushDaemon() {
for _ = range time.NewTicker(flushInterval).C { for range time.NewTicker(flushInterval).C {
l.lockAndFlushAll() l.lockAndFlushAll()
} }
} }

View File

@ -16,11 +16,10 @@
// File I/O for logs. // File I/O for logs.
package glog package klog
import ( import (
"errors" "errors"
"flag"
"fmt" "fmt"
"os" "os"
"os/user" "os/user"
@ -36,13 +35,9 @@ var MaxSize uint64 = 1024 * 1024 * 1800
// logDirs lists the candidate directories for new log files. // logDirs lists the candidate directories for new log files.
var logDirs []string var logDirs []string
// If non-empty, overrides the choice of directory in which to write logs.
// See createLogDirs for the full list of possible destinations.
var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory")
func createLogDirs() { func createLogDirs() {
if *logDir != "" { if logging.logDir != "" {
logDirs = append(logDirs, *logDir) logDirs = append(logDirs, logging.logDir)
} }
logDirs = append(logDirs, os.TempDir()) logDirs = append(logDirs, os.TempDir())
} }
@ -103,6 +98,13 @@ var onceLogDirs sync.Once
// successfully, create also attempts to update the symlink for that tag, ignoring // successfully, create also attempts to update the symlink for that tag, ignoring
// errors. // errors.
func create(tag string, t time.Time) (f *os.File, filename string, err error) { func create(tag string, t time.Time) (f *os.File, filename string, err error) {
if logging.logFile != "" {
f, err := os.Create(logging.logFile)
if err == nil {
return f, logging.logFile, nil
}
return nil, "", fmt.Errorf("log: unable to create log: %v", err)
}
onceLogDirs.Do(createLogDirs) onceLogDirs.Do(createLogDirs)
if len(logDirs) == 0 { if len(logDirs) == 0 {
return nil, "", errors.New("log: no log dirs") return nil, "", errors.New("log: no log dirs")

View File

@ -82,7 +82,7 @@ docker-machine create \
# Set up local docker to talk to that machine # Set up local docker to talk to that machine
eval $(docker-machine env ${KUBE_BUILD_VM}) eval $(docker-machine env ${KUBE_BUILD_VM})
# Pin down the port that rsync will be exposed on on the remote machine # Pin down the port that rsync will be exposed on the remote machine
export KUBE_RSYNC_PORT=8730 export KUBE_RSYNC_PORT=8730
# forward local 8730 to that machine so that rsync works # forward local 8730 to that machine so that rsync works

View File

@ -82,4 +82,23 @@ const (
// //
// Not all cloud providers support this annotation, though AWS & GCE do. // Not all cloud providers support this annotation, though AWS & GCE do.
AnnotationLoadBalancerSourceRangesKey = "service.beta.kubernetes.io/load-balancer-source-ranges" AnnotationLoadBalancerSourceRangesKey = "service.beta.kubernetes.io/load-balancer-source-ranges"
// EndpointsLastChangeTriggerTime is the annotation key, set for endpoints objects, that
// represents the timestamp (stored as RFC 3339 date-time string, e.g. '2018-10-22T19:32:52.1Z')
// of the last change, of some Pod or Service object, that triggered the endpoints object change.
// In other words, if a Pod / Service changed at time T0, that change was observed by endpoints
// controller at T1, and the Endpoints object was changed at T2, the
// EndpointsLastChangeTriggerTime would be set to T0.
//
// The "endpoints change trigger" here means any Pod or Service change that resulted in the
// Endpoints object change.
//
// Given the definition of the "endpoints change trigger", please note that this annotation will
// be set ONLY for endpoints object changes triggered by either Pod or Service change. If the
// Endpoints object changes due to other reasons, this annotation won't be set (or updated if it's
// already set).
//
// This annotation will be used to compute the in-cluster network programming latency SLI, see
// https://github.com/kubernetes/community/blob/master/sig-scalability/slos/network_programming_latency.md
EndpointsLastChangeTriggerTime = "endpoints.kubernetes.io/last-change-trigger-time"
) )

View File

@ -26,19 +26,19 @@ import (
const ( const (
// NamespaceDefault means the object is in the default namespace which is applied when not specified by clients // NamespaceDefault means the object is in the default namespace which is applied when not specified by clients
NamespaceDefault string = "default" NamespaceDefault = "default"
// NamespaceAll is the default argument to specify on a context when you want to list or filter resources across all namespaces // NamespaceAll is the default argument to specify on a context when you want to list or filter resources across all namespaces
NamespaceAll string = "" NamespaceAll = ""
// NamespaceNone is the argument for a context when there is no namespace. // NamespaceNone is the argument for a context when there is no namespace.
NamespaceNone string = "" NamespaceNone = ""
// NamespaceSystem is the system namespace where we place system components. // NamespaceSystem is the system namespace where we place system components.
NamespaceSystem string = "kube-system" NamespaceSystem = "kube-system"
// NamespacePublic is the namespace where we place public info (ConfigMaps) // NamespacePublic is the namespace where we place public info (ConfigMaps)
NamespacePublic string = "kube-public" NamespacePublic = "kube-public"
// NamespaceNodeLease is the namespace where we place node lease objects (used for node heartbeats) // NamespaceNodeLease is the namespace where we place node lease objects (used for node heartbeats)
NamespaceNodeLease string = "kube-node-lease" NamespaceNodeLease = "kube-node-lease"
// TerminationMessagePathDefault means the default path to capture the application termination message running in a container // TerminationMessagePathDefault means the default path to capture the application termination message running in a container
TerminationMessagePathDefault string = "/dev/termination-log" TerminationMessagePathDefault = "/dev/termination-log"
) )
// Volume represents a named volume in a pod that may be accessed by any containers in the pod. // Volume represents a named volume in a pod that may be accessed by any containers in the pod.
@ -175,7 +175,7 @@ type PersistentVolumeSource struct {
HostPath *HostPathVolumeSource HostPath *HostPathVolumeSource
// Glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod // Glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod
// +optional // +optional
Glusterfs *GlusterfsVolumeSource Glusterfs *GlusterfsPersistentVolumeSource
// NFS represents an NFS mount on the host that shares a pod's lifetime // NFS represents an NFS mount on the host that shares a pod's lifetime
// +optional // +optional
NFS *NFSVolumeSource NFS *NFSVolumeSource
@ -229,7 +229,7 @@ type PersistentVolumeSource struct {
// More info: https://releases.k8s.io/HEAD/examples/volumes/storageos/README.md // More info: https://releases.k8s.io/HEAD/examples/volumes/storageos/README.md
// +optional // +optional
StorageOS *StorageOSPersistentVolumeSource StorageOS *StorageOSPersistentVolumeSource
// CSI (Container Storage Interface) represents storage that handled by an external CSI driver (Beta feature). // CSI (Container Storage Interface) represents storage that handled by an external CSI driver.
// +optional // +optional
CSI *CSIPersistentVolumeSource CSI *CSIPersistentVolumeSource
} }
@ -298,7 +298,7 @@ type PersistentVolumeSpec struct {
MountOptions []string MountOptions []string
// volumeMode defines if a volume is intended to be used with a formatted filesystem // volumeMode defines if a volume is intended to be used with a formatted filesystem
// or to remain in raw block state. Value of Filesystem is implied when not included in spec. // or to remain in raw block state. Value of Filesystem is implied when not included in spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
VolumeMode *PersistentVolumeMode VolumeMode *PersistentVolumeMode
// NodeAffinity defines constraints that limit what nodes this volume can be accessed from. // NodeAffinity defines constraints that limit what nodes this volume can be accessed from.
@ -410,7 +410,7 @@ type PersistentVolumeClaimSpec struct {
StorageClassName *string StorageClassName *string
// volumeMode defines what type of volume is required by the claim. // volumeMode defines what type of volume is required by the claim.
// Value of Filesystem is implied when not included in claim spec. // Value of Filesystem is implied when not included in claim spec.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
VolumeMode *PersistentVolumeMode VolumeMode *PersistentVolumeMode
// This field requires the VolumeSnapshotDataSource alpha feature gate to be // This field requires the VolumeSnapshotDataSource alpha feature gate to be
@ -935,6 +935,30 @@ type GlusterfsVolumeSource struct {
ReadOnly bool ReadOnly bool
} }
// Represents a Glusterfs mount that lasts the lifetime of a pod.
// Glusterfs volumes do not support ownership management or SELinux relabeling.
type GlusterfsPersistentVolumeSource struct {
// EndpointsName is the endpoint name that details Glusterfs topology.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
EndpointsName string
// Path is the Glusterfs volume path.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
Path string
// ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions.
// Defaults to false.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
ReadOnly bool
// EndpointsNamespace is the namespace that contains Glusterfs endpoint.
// If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC.
// More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod
// +optional
EndpointsNamespace *string
}
// Represents a Rados Block Device mount that lasts the lifetime of a pod. // Represents a Rados Block Device mount that lasts the lifetime of a pod.
// RBD volumes support ownership management and SELinux relabeling. // RBD volumes support ownership management and SELinux relabeling.
type RBDVolumeSource struct { type RBDVolumeSource struct {
@ -1523,7 +1547,7 @@ type LocalVolumeSource struct {
FSType *string FSType *string
} }
// Represents storage that is managed by an external CSI volume driver (Beta feature) // Represents storage that is managed by an external CSI volume driver.
type CSIPersistentVolumeSource struct { type CSIPersistentVolumeSource struct {
// Driver is the name of the driver to use for this volume. // Driver is the name of the driver to use for this volume.
// Required. // Required.
@ -1944,7 +1968,7 @@ type Container struct {
// +optional // +optional
VolumeMounts []VolumeMount VolumeMounts []VolumeMount
// volumeDevices is the list of block devices to be used by the container. // volumeDevices is the list of block devices to be used by the container.
// This is an alpha feature and may change in the future. // This is a beta feature.
// +optional // +optional
VolumeDevices []VolumeDevice VolumeDevices []VolumeDevice
// +optional // +optional
@ -2597,6 +2621,11 @@ type PodSpec struct {
// This is an alpha feature and may change in the future. // This is an alpha feature and may change in the future.
// +optional // +optional
RuntimeClassName *string RuntimeClassName *string
// EnableServiceLinks indicates whether information about services should be injected into pod's
// environment variables, matching the syntax of Docker links.
// If not specified, the default is true.
// +optional
EnableServiceLinks *bool
} }
// HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the // HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the

View File

@ -1498,6 +1498,27 @@ func (in *GitRepoVolumeSource) DeepCopy() *GitRepoVolumeSource {
return out return out
} }
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GlusterfsPersistentVolumeSource) DeepCopyInto(out *GlusterfsPersistentVolumeSource) {
*out = *in
if in.EndpointsNamespace != nil {
in, out := &in.EndpointsNamespace, &out.EndpointsNamespace
*out = new(string)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GlusterfsPersistentVolumeSource.
func (in *GlusterfsPersistentVolumeSource) DeepCopy() *GlusterfsPersistentVolumeSource {
if in == nil {
return nil
}
out := new(GlusterfsPersistentVolumeSource)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GlusterfsVolumeSource) DeepCopyInto(out *GlusterfsVolumeSource) { func (in *GlusterfsVolumeSource) DeepCopyInto(out *GlusterfsVolumeSource) {
*out = *in *out = *in
@ -2808,8 +2829,8 @@ func (in *PersistentVolumeSource) DeepCopyInto(out *PersistentVolumeSource) {
} }
if in.Glusterfs != nil { if in.Glusterfs != nil {
in, out := &in.Glusterfs, &out.Glusterfs in, out := &in.Glusterfs, &out.Glusterfs
*out = new(GlusterfsVolumeSource) *out = new(GlusterfsPersistentVolumeSource)
**out = **in (*in).DeepCopyInto(*out)
} }
if in.NFS != nil { if in.NFS != nil {
in, out := &in.NFS, &out.NFS in, out := &in.NFS, &out.NFS
@ -3556,6 +3577,11 @@ func (in *PodSpec) DeepCopyInto(out *PodSpec) {
*out = new(string) *out = new(string)
**out = **in **out = **in
} }
if in.EnableServiceLinks != nil {
in, out := &in.EnableServiceLinks, &out.EnableServiceLinks
*out = new(bool)
**out = **in
}
return return
} }

File diff suppressed because it is too large Load Diff

View File

@ -22,8 +22,8 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/golang/glog"
"google.golang.org/grpc" "google.golang.org/grpc"
"k8s.io/klog"
internalapi "k8s.io/kubernetes/pkg/kubelet/apis/cri" internalapi "k8s.io/kubernetes/pkg/kubelet/apis/cri"
runtimeapi "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2" runtimeapi "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2"
@ -38,7 +38,7 @@ type RemoteImageService struct {
// NewRemoteImageService creates a new internalapi.ImageManagerService. // NewRemoteImageService creates a new internalapi.ImageManagerService.
func NewRemoteImageService(endpoint string, connectionTimeout time.Duration) (internalapi.ImageManagerService, error) { func NewRemoteImageService(endpoint string, connectionTimeout time.Duration) (internalapi.ImageManagerService, error) {
glog.V(3).Infof("Connecting to image service %s", endpoint) klog.V(3).Infof("Connecting to image service %s", endpoint)
addr, dailer, err := util.GetAddressAndDialer(endpoint) addr, dailer, err := util.GetAddressAndDialer(endpoint)
if err != nil { if err != nil {
return nil, err return nil, err
@ -49,7 +49,7 @@ func NewRemoteImageService(endpoint string, connectionTimeout time.Duration) (in
conn, err := grpc.DialContext(ctx, addr, grpc.WithInsecure(), grpc.WithDialer(dailer), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize))) conn, err := grpc.DialContext(ctx, addr, grpc.WithInsecure(), grpc.WithDialer(dailer), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize)))
if err != nil { if err != nil {
glog.Errorf("Connect remote image service %s failed: %v", addr, err) klog.Errorf("Connect remote image service %s failed: %v", addr, err)
return nil, err return nil, err
} }
@ -68,7 +68,7 @@ func (r *RemoteImageService) ListImages(filter *runtimeapi.ImageFilter) ([]*runt
Filter: filter, Filter: filter,
}) })
if err != nil { if err != nil {
glog.Errorf("ListImages with filter %+v from image service failed: %v", filter, err) klog.Errorf("ListImages with filter %+v from image service failed: %v", filter, err)
return nil, err return nil, err
} }
@ -84,14 +84,14 @@ func (r *RemoteImageService) ImageStatus(image *runtimeapi.ImageSpec) (*runtimea
Image: image, Image: image,
}) })
if err != nil { if err != nil {
glog.Errorf("ImageStatus %q from image service failed: %v", image.Image, err) klog.Errorf("ImageStatus %q from image service failed: %v", image.Image, err)
return nil, err return nil, err
} }
if resp.Image != nil { if resp.Image != nil {
if resp.Image.Id == "" || resp.Image.Size_ == 0 { if resp.Image.Id == "" || resp.Image.Size_ == 0 {
errorMessage := fmt.Sprintf("Id or size of image %q is not set", image.Image) errorMessage := fmt.Sprintf("Id or size of image %q is not set", image.Image)
glog.Errorf("ImageStatus failed: %s", errorMessage) klog.Errorf("ImageStatus failed: %s", errorMessage)
return nil, errors.New(errorMessage) return nil, errors.New(errorMessage)
} }
} }
@ -109,13 +109,13 @@ func (r *RemoteImageService) PullImage(image *runtimeapi.ImageSpec, auth *runtim
Auth: auth, Auth: auth,
}) })
if err != nil { if err != nil {
glog.Errorf("PullImage %q from image service failed: %v", image.Image, err) klog.Errorf("PullImage %q from image service failed: %v", image.Image, err)
return "", err return "", err
} }
if resp.ImageRef == "" { if resp.ImageRef == "" {
errorMessage := fmt.Sprintf("imageRef of image %q is not set", image.Image) errorMessage := fmt.Sprintf("imageRef of image %q is not set", image.Image)
glog.Errorf("PullImage failed: %s", errorMessage) klog.Errorf("PullImage failed: %s", errorMessage)
return "", errors.New(errorMessage) return "", errors.New(errorMessage)
} }
@ -131,7 +131,7 @@ func (r *RemoteImageService) RemoveImage(image *runtimeapi.ImageSpec) error {
Image: image, Image: image,
}) })
if err != nil { if err != nil {
glog.Errorf("RemoveImage %q from image service failed: %v", image.Image, err) klog.Errorf("RemoveImage %q from image service failed: %v", image.Image, err)
return err return err
} }
@ -147,7 +147,7 @@ func (r *RemoteImageService) ImageFsInfo() ([]*runtimeapi.FilesystemUsage, error
resp, err := r.imageClient.ImageFsInfo(ctx, &runtimeapi.ImageFsInfoRequest{}) resp, err := r.imageClient.ImageFsInfo(ctx, &runtimeapi.ImageFsInfoRequest{})
if err != nil { if err != nil {
glog.Errorf("ImageFsInfo from image service failed: %v", err) klog.Errorf("ImageFsInfo from image service failed: %v", err)
return nil, err return nil, err
} }
return resp.GetImageFilesystems(), nil return resp.GetImageFilesystems(), nil

View File

@ -23,8 +23,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/golang/glog"
"google.golang.org/grpc" "google.golang.org/grpc"
"k8s.io/klog"
internalapi "k8s.io/kubernetes/pkg/kubelet/apis/cri" internalapi "k8s.io/kubernetes/pkg/kubelet/apis/cri"
runtimeapi "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2" runtimeapi "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2"
@ -40,7 +40,7 @@ type RemoteRuntimeService struct {
// NewRemoteRuntimeService creates a new internalapi.RuntimeService. // NewRemoteRuntimeService creates a new internalapi.RuntimeService.
func NewRemoteRuntimeService(endpoint string, connectionTimeout time.Duration) (internalapi.RuntimeService, error) { func NewRemoteRuntimeService(endpoint string, connectionTimeout time.Duration) (internalapi.RuntimeService, error) {
glog.V(3).Infof("Connecting to runtime service %s", endpoint) klog.V(3).Infof("Connecting to runtime service %s", endpoint)
addr, dailer, err := util.GetAddressAndDialer(endpoint) addr, dailer, err := util.GetAddressAndDialer(endpoint)
if err != nil { if err != nil {
return nil, err return nil, err
@ -50,7 +50,7 @@ func NewRemoteRuntimeService(endpoint string, connectionTimeout time.Duration) (
conn, err := grpc.DialContext(ctx, addr, grpc.WithInsecure(), grpc.WithDialer(dailer), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize))) conn, err := grpc.DialContext(ctx, addr, grpc.WithInsecure(), grpc.WithDialer(dailer), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize)))
if err != nil { if err != nil {
glog.Errorf("Connect remote runtime %s failed: %v", addr, err) klog.Errorf("Connect remote runtime %s failed: %v", addr, err)
return nil, err return nil, err
} }
@ -69,7 +69,7 @@ func (r *RemoteRuntimeService) Version(apiVersion string) (*runtimeapi.VersionRe
Version: apiVersion, Version: apiVersion,
}) })
if err != nil { if err != nil {
glog.Errorf("Version from runtime service failed: %v", err) klog.Errorf("Version from runtime service failed: %v", err)
return nil, err return nil, err
} }
@ -93,13 +93,13 @@ func (r *RemoteRuntimeService) RunPodSandbox(config *runtimeapi.PodSandboxConfig
RuntimeHandler: runtimeHandler, RuntimeHandler: runtimeHandler,
}) })
if err != nil { if err != nil {
glog.Errorf("RunPodSandbox from runtime service failed: %v", err) klog.Errorf("RunPodSandbox from runtime service failed: %v", err)
return "", err return "", err
} }
if resp.PodSandboxId == "" { if resp.PodSandboxId == "" {
errorMessage := fmt.Sprintf("PodSandboxId is not set for sandbox %q", config.GetMetadata()) errorMessage := fmt.Sprintf("PodSandboxId is not set for sandbox %q", config.GetMetadata())
glog.Errorf("RunPodSandbox failed: %s", errorMessage) klog.Errorf("RunPodSandbox failed: %s", errorMessage)
return "", errors.New(errorMessage) return "", errors.New(errorMessage)
} }
@ -116,7 +116,7 @@ func (r *RemoteRuntimeService) StopPodSandbox(podSandBoxID string) error {
PodSandboxId: podSandBoxID, PodSandboxId: podSandBoxID,
}) })
if err != nil { if err != nil {
glog.Errorf("StopPodSandbox %q from runtime service failed: %v", podSandBoxID, err) klog.Errorf("StopPodSandbox %q from runtime service failed: %v", podSandBoxID, err)
return err return err
} }
@ -133,7 +133,7 @@ func (r *RemoteRuntimeService) RemovePodSandbox(podSandBoxID string) error {
PodSandboxId: podSandBoxID, PodSandboxId: podSandBoxID,
}) })
if err != nil { if err != nil {
glog.Errorf("RemovePodSandbox %q from runtime service failed: %v", podSandBoxID, err) klog.Errorf("RemovePodSandbox %q from runtime service failed: %v", podSandBoxID, err)
return err return err
} }
@ -170,7 +170,7 @@ func (r *RemoteRuntimeService) ListPodSandbox(filter *runtimeapi.PodSandboxFilte
Filter: filter, Filter: filter,
}) })
if err != nil { if err != nil {
glog.Errorf("ListPodSandbox with filter %+v from runtime service failed: %v", filter, err) klog.Errorf("ListPodSandbox with filter %+v from runtime service failed: %v", filter, err)
return nil, err return nil, err
} }
@ -188,13 +188,13 @@ func (r *RemoteRuntimeService) CreateContainer(podSandBoxID string, config *runt
SandboxConfig: sandboxConfig, SandboxConfig: sandboxConfig,
}) })
if err != nil { if err != nil {
glog.Errorf("CreateContainer in sandbox %q from runtime service failed: %v", podSandBoxID, err) klog.Errorf("CreateContainer in sandbox %q from runtime service failed: %v", podSandBoxID, err)
return "", err return "", err
} }
if resp.ContainerId == "" { if resp.ContainerId == "" {
errorMessage := fmt.Sprintf("ContainerId is not set for container %q", config.GetMetadata()) errorMessage := fmt.Sprintf("ContainerId is not set for container %q", config.GetMetadata())
glog.Errorf("CreateContainer failed: %s", errorMessage) klog.Errorf("CreateContainer failed: %s", errorMessage)
return "", errors.New(errorMessage) return "", errors.New(errorMessage)
} }
@ -210,7 +210,7 @@ func (r *RemoteRuntimeService) StartContainer(containerID string) error {
ContainerId: containerID, ContainerId: containerID,
}) })
if err != nil { if err != nil {
glog.Errorf("StartContainer %q from runtime service failed: %v", containerID, err) klog.Errorf("StartContainer %q from runtime service failed: %v", containerID, err)
return err return err
} }
@ -230,7 +230,7 @@ func (r *RemoteRuntimeService) StopContainer(containerID string, timeout int64)
Timeout: timeout, Timeout: timeout,
}) })
if err != nil { if err != nil {
glog.Errorf("StopContainer %q from runtime service failed: %v", containerID, err) klog.Errorf("StopContainer %q from runtime service failed: %v", containerID, err)
return err return err
} }
@ -247,7 +247,7 @@ func (r *RemoteRuntimeService) RemoveContainer(containerID string) error {
ContainerId: containerID, ContainerId: containerID,
}) })
if err != nil { if err != nil {
glog.Errorf("RemoveContainer %q from runtime service failed: %v", containerID, err) klog.Errorf("RemoveContainer %q from runtime service failed: %v", containerID, err)
return err return err
} }
@ -263,7 +263,7 @@ func (r *RemoteRuntimeService) ListContainers(filter *runtimeapi.ContainerFilter
Filter: filter, Filter: filter,
}) })
if err != nil { if err != nil {
glog.Errorf("ListContainers with filter %+v from runtime service failed: %v", filter, err) klog.Errorf("ListContainers with filter %+v from runtime service failed: %v", filter, err)
return nil, err return nil, err
} }
@ -279,13 +279,13 @@ func (r *RemoteRuntimeService) ContainerStatus(containerID string) (*runtimeapi.
ContainerId: containerID, ContainerId: containerID,
}) })
if err != nil { if err != nil {
glog.Errorf("ContainerStatus %q from runtime service failed: %v", containerID, err) klog.Errorf("ContainerStatus %q from runtime service failed: %v", containerID, err)
return nil, err return nil, err
} }
if resp.Status != nil { if resp.Status != nil {
if err := verifyContainerStatus(resp.Status); err != nil { if err := verifyContainerStatus(resp.Status); err != nil {
glog.Errorf("ContainerStatus of %q failed: %v", containerID, err) klog.Errorf("ContainerStatus of %q failed: %v", containerID, err)
return nil, err return nil, err
} }
} }
@ -303,7 +303,7 @@ func (r *RemoteRuntimeService) UpdateContainerResources(containerID string, reso
Linux: resources, Linux: resources,
}) })
if err != nil { if err != nil {
glog.Errorf("UpdateContainerResources %q from runtime service failed: %v", containerID, err) klog.Errorf("UpdateContainerResources %q from runtime service failed: %v", containerID, err)
return err return err
} }
@ -333,7 +333,7 @@ func (r *RemoteRuntimeService) ExecSync(containerID string, cmd []string, timeou
} }
resp, err := r.runtimeClient.ExecSync(ctx, req) resp, err := r.runtimeClient.ExecSync(ctx, req)
if err != nil { if err != nil {
glog.Errorf("ExecSync %s '%s' from runtime service failed: %v", containerID, strings.Join(cmd, " "), err) klog.Errorf("ExecSync %s '%s' from runtime service failed: %v", containerID, strings.Join(cmd, " "), err)
return nil, nil, err return nil, nil, err
} }
@ -355,13 +355,13 @@ func (r *RemoteRuntimeService) Exec(req *runtimeapi.ExecRequest) (*runtimeapi.Ex
resp, err := r.runtimeClient.Exec(ctx, req) resp, err := r.runtimeClient.Exec(ctx, req)
if err != nil { if err != nil {
glog.Errorf("Exec %s '%s' from runtime service failed: %v", req.ContainerId, strings.Join(req.Cmd, " "), err) klog.Errorf("Exec %s '%s' from runtime service failed: %v", req.ContainerId, strings.Join(req.Cmd, " "), err)
return nil, err return nil, err
} }
if resp.Url == "" { if resp.Url == "" {
errorMessage := "URL is not set" errorMessage := "URL is not set"
glog.Errorf("Exec failed: %s", errorMessage) klog.Errorf("Exec failed: %s", errorMessage)
return nil, errors.New(errorMessage) return nil, errors.New(errorMessage)
} }
@ -375,13 +375,13 @@ func (r *RemoteRuntimeService) Attach(req *runtimeapi.AttachRequest) (*runtimeap
resp, err := r.runtimeClient.Attach(ctx, req) resp, err := r.runtimeClient.Attach(ctx, req)
if err != nil { if err != nil {
glog.Errorf("Attach %s from runtime service failed: %v", req.ContainerId, err) klog.Errorf("Attach %s from runtime service failed: %v", req.ContainerId, err)
return nil, err return nil, err
} }
if resp.Url == "" { if resp.Url == "" {
errorMessage := "URL is not set" errorMessage := "URL is not set"
glog.Errorf("Exec failed: %s", errorMessage) klog.Errorf("Exec failed: %s", errorMessage)
return nil, errors.New(errorMessage) return nil, errors.New(errorMessage)
} }
return resp, nil return resp, nil
@ -394,13 +394,13 @@ func (r *RemoteRuntimeService) PortForward(req *runtimeapi.PortForwardRequest) (
resp, err := r.runtimeClient.PortForward(ctx, req) resp, err := r.runtimeClient.PortForward(ctx, req)
if err != nil { if err != nil {
glog.Errorf("PortForward %s from runtime service failed: %v", req.PodSandboxId, err) klog.Errorf("PortForward %s from runtime service failed: %v", req.PodSandboxId, err)
return nil, err return nil, err
} }
if resp.Url == "" { if resp.Url == "" {
errorMessage := "URL is not set" errorMessage := "URL is not set"
glog.Errorf("Exec failed: %s", errorMessage) klog.Errorf("Exec failed: %s", errorMessage)
return nil, errors.New(errorMessage) return nil, errors.New(errorMessage)
} }
@ -435,13 +435,13 @@ func (r *RemoteRuntimeService) Status() (*runtimeapi.RuntimeStatus, error) {
resp, err := r.runtimeClient.Status(ctx, &runtimeapi.StatusRequest{}) resp, err := r.runtimeClient.Status(ctx, &runtimeapi.StatusRequest{})
if err != nil { if err != nil {
glog.Errorf("Status from runtime service failed: %v", err) klog.Errorf("Status from runtime service failed: %v", err)
return nil, err return nil, err
} }
if resp.Status == nil || len(resp.Status.Conditions) < 2 { if resp.Status == nil || len(resp.Status.Conditions) < 2 {
errorMessage := "RuntimeReady or NetworkReady condition are not set" errorMessage := "RuntimeReady or NetworkReady condition are not set"
glog.Errorf("Status failed: %s", errorMessage) klog.Errorf("Status failed: %s", errorMessage)
return nil, errors.New(errorMessage) return nil, errors.New(errorMessage)
} }
@ -457,7 +457,7 @@ func (r *RemoteRuntimeService) ContainerStats(containerID string) (*runtimeapi.C
ContainerId: containerID, ContainerId: containerID,
}) })
if err != nil { if err != nil {
glog.Errorf("ContainerStatus %q from runtime service failed: %v", containerID, err) klog.Errorf("ContainerStatus %q from runtime service failed: %v", containerID, err)
return nil, err return nil, err
} }
@ -474,7 +474,7 @@ func (r *RemoteRuntimeService) ListContainerStats(filter *runtimeapi.ContainerSt
Filter: filter, Filter: filter,
}) })
if err != nil { if err != nil {
glog.Errorf("ListContainerStats with filter %+v from runtime service failed: %v", filter, err) klog.Errorf("ListContainerStats with filter %+v from runtime service failed: %v", filter, err)
return nil, err return nil, err
} }
@ -487,7 +487,7 @@ func (r *RemoteRuntimeService) ReopenContainerLog(containerID string) error {
_, err := r.runtimeClient.ReopenContainerLog(ctx, &runtimeapi.ReopenContainerLogRequest{ContainerId: containerID}) _, err := r.runtimeClient.ReopenContainerLog(ctx, &runtimeapi.ReopenContainerLogRequest{ContainerId: containerID})
if err != nil { if err != nil {
glog.Errorf("ReopenContainerLog %q from runtime service failed: %v", containerID, err) klog.Errorf("ReopenContainerLog %q from runtime service failed: %v", containerID, err)
return err return err
} }
return nil return nil

View File

@ -30,7 +30,7 @@ import (
utilruntime "k8s.io/apimachinery/pkg/util/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime"
api "k8s.io/kubernetes/pkg/apis/core" api "k8s.io/kubernetes/pkg/apis/core"
"github.com/golang/glog" "k8s.io/klog"
) )
func handleHttpStreams(req *http.Request, w http.ResponseWriter, portForwarder PortForwarder, podName string, uid types.UID, supportedPortForwardProtocols []string, idleTimeout, streamCreationTimeout time.Duration) error { func handleHttpStreams(req *http.Request, w http.ResponseWriter, portForwarder PortForwarder, podName string, uid types.UID, supportedPortForwardProtocols []string, idleTimeout, streamCreationTimeout time.Duration) error {
@ -42,7 +42,7 @@ func handleHttpStreams(req *http.Request, w http.ResponseWriter, portForwarder P
} }
streamChan := make(chan httpstream.Stream, 1) streamChan := make(chan httpstream.Stream, 1)
glog.V(5).Infof("Upgrading port forward response") klog.V(5).Infof("Upgrading port forward response")
upgrader := spdy.NewResponseUpgrader() upgrader := spdy.NewResponseUpgrader()
conn := upgrader.UpgradeResponse(w, req, httpStreamReceived(streamChan)) conn := upgrader.UpgradeResponse(w, req, httpStreamReceived(streamChan))
if conn == nil { if conn == nil {
@ -50,7 +50,7 @@ func handleHttpStreams(req *http.Request, w http.ResponseWriter, portForwarder P
} }
defer conn.Close() defer conn.Close()
glog.V(5).Infof("(conn=%p) setting port forwarding streaming connection idle timeout to %v", conn, idleTimeout) klog.V(5).Infof("(conn=%p) setting port forwarding streaming connection idle timeout to %v", conn, idleTimeout)
conn.SetIdleTimeout(idleTimeout) conn.SetIdleTimeout(idleTimeout)
h := &httpStreamHandler{ h := &httpStreamHandler{
@ -121,11 +121,11 @@ func (h *httpStreamHandler) getStreamPair(requestID string) (*httpStreamPair, bo
defer h.streamPairsLock.Unlock() defer h.streamPairsLock.Unlock()
if p, ok := h.streamPairs[requestID]; ok { if p, ok := h.streamPairs[requestID]; ok {
glog.V(5).Infof("(conn=%p, request=%s) found existing stream pair", h.conn, requestID) klog.V(5).Infof("(conn=%p, request=%s) found existing stream pair", h.conn, requestID)
return p, false return p, false
} }
glog.V(5).Infof("(conn=%p, request=%s) creating new stream pair", h.conn, requestID) klog.V(5).Infof("(conn=%p, request=%s) creating new stream pair", h.conn, requestID)
p := newPortForwardPair(requestID) p := newPortForwardPair(requestID)
h.streamPairs[requestID] = p h.streamPairs[requestID] = p
@ -143,7 +143,7 @@ func (h *httpStreamHandler) monitorStreamPair(p *httpStreamPair, timeout <-chan
utilruntime.HandleError(err) utilruntime.HandleError(err)
p.printError(err.Error()) p.printError(err.Error())
case <-p.complete: case <-p.complete:
glog.V(5).Infof("(conn=%v, request=%s) successfully received error and data streams", h.conn, p.requestID) klog.V(5).Infof("(conn=%v, request=%s) successfully received error and data streams", h.conn, p.requestID)
} }
h.removeStreamPair(p.requestID) h.removeStreamPair(p.requestID)
} }
@ -170,7 +170,7 @@ func (h *httpStreamHandler) removeStreamPair(requestID string) {
func (h *httpStreamHandler) requestID(stream httpstream.Stream) string { func (h *httpStreamHandler) requestID(stream httpstream.Stream) string {
requestID := stream.Headers().Get(api.PortForwardRequestIDHeader) requestID := stream.Headers().Get(api.PortForwardRequestIDHeader)
if len(requestID) == 0 { if len(requestID) == 0 {
glog.V(5).Infof("(conn=%p) stream received without %s header", h.conn, api.PortForwardRequestIDHeader) klog.V(5).Infof("(conn=%p) stream received without %s header", h.conn, api.PortForwardRequestIDHeader)
// If we get here, it's because the connection came from an older client // If we get here, it's because the connection came from an older client
// that isn't generating the request id header // that isn't generating the request id header
// (https://github.com/kubernetes/kubernetes/blob/843134885e7e0b360eb5441e85b1410a8b1a7a0c/pkg/client/unversioned/portforward/portforward.go#L258-L287) // (https://github.com/kubernetes/kubernetes/blob/843134885e7e0b360eb5441e85b1410a8b1a7a0c/pkg/client/unversioned/portforward/portforward.go#L258-L287)
@ -197,7 +197,7 @@ func (h *httpStreamHandler) requestID(stream httpstream.Stream) string {
requestID = strconv.Itoa(int(stream.Identifier()) - 2) requestID = strconv.Itoa(int(stream.Identifier()) - 2)
} }
glog.V(5).Infof("(conn=%p) automatically assigning request ID=%q from stream type=%s, stream ID=%d", h.conn, requestID, streamType, stream.Identifier()) klog.V(5).Infof("(conn=%p) automatically assigning request ID=%q from stream type=%s, stream ID=%d", h.conn, requestID, streamType, stream.Identifier())
} }
return requestID return requestID
} }
@ -206,17 +206,17 @@ func (h *httpStreamHandler) requestID(stream httpstream.Stream) string {
// streams, invoking portForward for each complete stream pair. The loop exits // streams, invoking portForward for each complete stream pair. The loop exits
// when the httpstream.Connection is closed. // when the httpstream.Connection is closed.
func (h *httpStreamHandler) run() { func (h *httpStreamHandler) run() {
glog.V(5).Infof("(conn=%p) waiting for port forward streams", h.conn) klog.V(5).Infof("(conn=%p) waiting for port forward streams", h.conn)
Loop: Loop:
for { for {
select { select {
case <-h.conn.CloseChan(): case <-h.conn.CloseChan():
glog.V(5).Infof("(conn=%p) upgraded connection closed", h.conn) klog.V(5).Infof("(conn=%p) upgraded connection closed", h.conn)
break Loop break Loop
case stream := <-h.streamChan: case stream := <-h.streamChan:
requestID := h.requestID(stream) requestID := h.requestID(stream)
streamType := stream.Headers().Get(api.StreamType) streamType := stream.Headers().Get(api.StreamType)
glog.V(5).Infof("(conn=%p, request=%s) received new stream of type %s", h.conn, requestID, streamType) klog.V(5).Infof("(conn=%p, request=%s) received new stream of type %s", h.conn, requestID, streamType)
p, created := h.getStreamPair(requestID) p, created := h.getStreamPair(requestID)
if created { if created {
@ -242,9 +242,9 @@ func (h *httpStreamHandler) portForward(p *httpStreamPair) {
portString := p.dataStream.Headers().Get(api.PortHeader) portString := p.dataStream.Headers().Get(api.PortHeader)
port, _ := strconv.ParseInt(portString, 10, 32) port, _ := strconv.ParseInt(portString, 10, 32)
glog.V(5).Infof("(conn=%p, request=%s) invoking forwarder.PortForward for port %s", h.conn, p.requestID, portString) klog.V(5).Infof("(conn=%p, request=%s) invoking forwarder.PortForward for port %s", h.conn, p.requestID, portString)
err := h.forwarder.PortForward(h.pod, h.uid, int32(port), p.dataStream) err := h.forwarder.PortForward(h.pod, h.uid, int32(port), p.dataStream)
glog.V(5).Infof("(conn=%p, request=%s) done invoking forwarder.PortForward for port %s", h.conn, p.requestID, portString) klog.V(5).Infof("(conn=%p, request=%s) done invoking forwarder.PortForward for port %s", h.conn, p.requestID, portString)
if err != nil { if err != nil {
msg := fmt.Errorf("error forwarding port %d to pod %s, uid %v: %v", port, h.pod, h.uid, err) msg := fmt.Errorf("error forwarding port %d to pod %s, uid %v: %v", port, h.pod, h.uid, err)

View File

@ -26,7 +26,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/golang/glog" "k8s.io/klog"
"k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/runtime"
@ -185,9 +185,9 @@ func (h *websocketStreamHandler) portForward(p *websocketStreamPair) {
defer p.dataStream.Close() defer p.dataStream.Close()
defer p.errorStream.Close() defer p.errorStream.Close()
glog.V(5).Infof("(conn=%p) invoking forwarder.PortForward for port %d", h.conn, p.port) klog.V(5).Infof("(conn=%p) invoking forwarder.PortForward for port %d", h.conn, p.port)
err := h.forwarder.PortForward(h.pod, h.uid, p.port, p.dataStream) err := h.forwarder.PortForward(h.pod, h.uid, p.port, p.dataStream)
glog.V(5).Infof("(conn=%p) done invoking forwarder.PortForward for port %d", h.conn, p.port) klog.V(5).Infof("(conn=%p) done invoking forwarder.PortForward for port %d", h.conn, p.port)
if err != nil { if err != nil {
msg := fmt.Errorf("error forwarding port %d to pod %s, uid %v: %v", p.port, h.pod, h.uid, err) msg := fmt.Errorf("error forwarding port %d to pod %s, uid %v: %v", p.port, h.pod, h.uid, err)

View File

@ -34,7 +34,7 @@ import (
"k8s.io/client-go/tools/remotecommand" "k8s.io/client-go/tools/remotecommand"
api "k8s.io/kubernetes/pkg/apis/core" api "k8s.io/kubernetes/pkg/apis/core"
"github.com/golang/glog" "k8s.io/klog"
) )
// Options contains details about which streams are required for // Options contains details about which streams are required for
@ -54,7 +54,7 @@ func NewOptions(req *http.Request) (*Options, error) {
stderr := req.FormValue(api.ExecStderrParam) == "1" stderr := req.FormValue(api.ExecStderrParam) == "1"
if tty && stderr { if tty && stderr {
// TODO: make this an error before we reach this method // TODO: make this an error before we reach this method
glog.V(4).Infof("Access to exec with tty and stderr is not supported, bypassing stderr") klog.V(4).Infof("Access to exec with tty and stderr is not supported, bypassing stderr")
stderr = false stderr = false
} }
@ -125,8 +125,7 @@ func createStreams(req *http.Request, w http.ResponseWriter, opts *Options, supp
func createHttpStreamStreams(req *http.Request, w http.ResponseWriter, opts *Options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*context, bool) { func createHttpStreamStreams(req *http.Request, w http.ResponseWriter, opts *Options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*context, bool) {
protocol, err := httpstream.Handshake(req, w, supportedStreamProtocols) protocol, err := httpstream.Handshake(req, w, supportedStreamProtocols)
if err != nil { if err != nil {
w.WriteHeader(http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return nil, false return nil, false
} }
@ -156,7 +155,7 @@ func createHttpStreamStreams(req *http.Request, w http.ResponseWriter, opts *Opt
case remotecommandconsts.StreamProtocolV2Name: case remotecommandconsts.StreamProtocolV2Name:
handler = &v2ProtocolHandler{} handler = &v2ProtocolHandler{}
case "": case "":
glog.V(4).Infof("Client did not request protocol negotiation. Falling back to %q", remotecommandconsts.StreamProtocolV1Name) klog.V(4).Infof("Client did not request protocol negotiation. Falling back to %q", remotecommandconsts.StreamProtocolV1Name)
fallthrough fallthrough
case remotecommandconsts.StreamProtocolV1Name: case remotecommandconsts.StreamProtocolV1Name:
handler = &v1ProtocolHandler{} handler = &v1ProtocolHandler{}

View File

@ -17,9 +17,6 @@ limitations under the License.
package util package util
import ( import (
"fmt"
"net/url"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
) )
@ -28,20 +25,3 @@ import (
func FromApiserverCache(opts *metav1.GetOptions) { func FromApiserverCache(opts *metav1.GetOptions) {
opts.ResourceVersion = "0" opts.ResourceVersion = "0"
} }
func parseEndpoint(endpoint string) (string, string, error) {
u, err := url.Parse(endpoint)
if err != nil {
return "", "", err
}
if u.Scheme == "tcp" {
return "tcp", u.Host, nil
} else if u.Scheme == "unix" {
return "unix", u.Path, nil
} else if u.Scheme == "" {
return "", "", fmt.Errorf("Using %q as endpoint is deprecated, please consider using full url format", endpoint)
} else {
return u.Scheme, "", fmt.Errorf("protocol %q not supported", u.Scheme)
}
}

View File

@ -21,11 +21,13 @@ package util
import ( import (
"fmt" "fmt"
"net" "net"
"net/url"
"os" "os"
"path/filepath"
"time" "time"
"github.com/golang/glog"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"k8s.io/klog"
) )
const ( const (
@ -72,8 +74,38 @@ func parseEndpointWithFallbackProtocol(endpoint string, fallbackProtocol string)
fallbackEndpoint := fallbackProtocol + "://" + endpoint fallbackEndpoint := fallbackProtocol + "://" + endpoint
protocol, addr, err = parseEndpoint(fallbackEndpoint) protocol, addr, err = parseEndpoint(fallbackEndpoint)
if err == nil { if err == nil {
glog.Warningf("Using %q as endpoint is deprecated, please consider using full url format %q.", endpoint, fallbackEndpoint) klog.Warningf("Using %q as endpoint is deprecated, please consider using full url format %q.", endpoint, fallbackEndpoint)
} }
} }
return return
} }
func parseEndpoint(endpoint string) (string, string, error) {
u, err := url.Parse(endpoint)
if err != nil {
return "", "", err
}
switch u.Scheme {
case "tcp":
return "tcp", u.Host, nil
case "unix":
return "unix", u.Path, nil
case "":
return "", "", fmt.Errorf("Using %q as endpoint is deprecated, please consider using full url format", endpoint)
default:
return u.Scheme, "", fmt.Errorf("protocol %q not supported", u.Scheme)
}
}
// LocalEndpoint returns the full path to a unix socket at the given endpoint
func LocalEndpoint(path, file string) string {
u := url.URL{
Scheme: unixProtocol,
Path: path,
}
return filepath.Join(u.String(), file+".sock")
}

View File

@ -40,3 +40,8 @@ func LockAndCheckSubPath(volumePath, subPath string) ([]uintptr, error) {
// UnlockPath empty implementation // UnlockPath empty implementation
func UnlockPath(fileHandles []uintptr) { func UnlockPath(fileHandles []uintptr) {
} }
// LocalEndpoint empty implementation
func LocalEndpoint(path, file string) string {
return ""
}

View File

@ -21,11 +21,16 @@ package util
import ( import (
"fmt" "fmt"
"net" "net"
"net/url"
"strings"
"time" "time"
"github.com/Microsoft/go-winio"
) )
const ( const (
tcpProtocol = "tcp" tcpProtocol = "tcp"
npipeProtocol = "npipe"
) )
func CreateListener(endpoint string) (net.Listener, error) { func CreateListener(endpoint string) (net.Listener, error) {
@ -33,11 +38,17 @@ func CreateListener(endpoint string) (net.Listener, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
if protocol != tcpProtocol {
return nil, fmt.Errorf("only support tcp endpoint")
}
return net.Listen(protocol, addr) switch protocol {
case tcpProtocol:
return net.Listen(tcpProtocol, addr)
case npipeProtocol:
return winio.ListenPipe(addr, nil)
default:
return nil, fmt.Errorf("only support tcp and npipe endpoint")
}
} }
func GetAddressAndDialer(endpoint string) (string, func(addr string, timeout time.Duration) (net.Conn, error), error) { func GetAddressAndDialer(endpoint string) (string, func(addr string, timeout time.Duration) (net.Conn, error), error) {
@ -45,13 +56,59 @@ func GetAddressAndDialer(endpoint string) (string, func(addr string, timeout tim
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
if protocol != tcpProtocol {
return "", nil, fmt.Errorf("only support tcp endpoint") if protocol == tcpProtocol {
return addr, tcpDial, nil
} }
return addr, dial, nil if protocol == npipeProtocol {
return addr, npipeDial, nil
}
return "", nil, fmt.Errorf("only support tcp and npipe endpoint")
} }
func dial(addr string, timeout time.Duration) (net.Conn, error) { func tcpDial(addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout(tcpProtocol, addr, timeout) return net.DialTimeout(tcpProtocol, addr, timeout)
} }
func npipeDial(addr string, timeout time.Duration) (net.Conn, error) {
return winio.DialPipe(addr, &timeout)
}
func parseEndpoint(endpoint string) (string, string, error) {
// url.Parse doesn't recognize \, so replace with / first.
endpoint = strings.Replace(endpoint, "\\", "/", -1)
u, err := url.Parse(endpoint)
if err != nil {
return "", "", err
}
if u.Scheme == "tcp" {
return "tcp", u.Host, nil
} else if u.Scheme == "npipe" {
if strings.HasPrefix(u.Path, "//./pipe") {
return "npipe", u.Path, nil
}
// fallback host if not provided.
host := u.Host
if host == "" {
host = "."
}
return "npipe", fmt.Sprintf("//%s%s", host, u.Path), nil
} else if u.Scheme == "" {
return "", "", fmt.Errorf("Using %q as endpoint is deprecated, please consider using full url format", endpoint)
} else {
return u.Scheme, "", fmt.Errorf("protocol %q not supported", u.Scheme)
}
}
// LocalEndpoint returns the full path to a windows named pipe
func LocalEndpoint(path, file string) string {
u := url.URL{
Scheme: npipeProtocol,
Path: path,
}
return u.String() + "//./pipe/" + file
}

6
vendor/k8s.io/utils/README.md generated vendored
View File

@ -48,6 +48,12 @@ an existing package to this repository.
- [Pointers](/pointers) provides some functions for pointer-based operations. - [Pointers](/pointers) provides some functions for pointer-based operations.
- [Io](/io) provides interfaces for working with file IO. Currently it provides
functionality for consistently reading a file.
- [NSEnter](/nsenter) provies interfaces for executing and interacting with
processes running within a namespace.
[Build Status]: https://travis-ci.org/kubernetes/utils.svg?branch=master [Build Status]: https://travis-ci.org/kubernetes/utils.svg?branch=master
[Go standard libs]: https://golang.org/pkg/#stdlib [Go standard libs]: https://golang.org/pkg/#stdlib
[api]: https://github.com/kubernetes/api [api]: https://github.com/kubernetes/api

37
vendor/k8s.io/utils/exec/exec.go generated vendored
View File

@ -60,6 +60,17 @@ type Cmd interface {
SetStdin(in io.Reader) SetStdin(in io.Reader)
SetStdout(out io.Writer) SetStdout(out io.Writer)
SetStderr(out io.Writer) SetStderr(out io.Writer)
SetEnv(env []string)
// StdoutPipe and StderrPipe for getting the process' Stdout and Stderr as
// Readers
StdoutPipe() (io.ReadCloser, error)
StderrPipe() (io.ReadCloser, error)
// Start and Wait are for running a process non-blocking
Start() error
Wait() error
// Stops the command by sending SIGTERM. It is not guaranteed the // Stops the command by sending SIGTERM. It is not guaranteed the
// process will stop before this function returns. If the process is not // process will stop before this function returns. If the process is not
// responding, an internal timer function will send a SIGKILL to force // responding, an internal timer function will send a SIGKILL to force
@ -121,6 +132,30 @@ func (cmd *cmdWrapper) SetStderr(out io.Writer) {
cmd.Stderr = out cmd.Stderr = out
} }
func (cmd *cmdWrapper) SetEnv(env []string) {
cmd.Env = env
}
func (cmd *cmdWrapper) StdoutPipe() (io.ReadCloser, error) {
r, err := (*osexec.Cmd)(cmd).StdoutPipe()
return r, handleError(err)
}
func (cmd *cmdWrapper) StderrPipe() (io.ReadCloser, error) {
r, err := (*osexec.Cmd)(cmd).StderrPipe()
return r, handleError(err)
}
func (cmd *cmdWrapper) Start() error {
err := (*osexec.Cmd)(cmd).Start()
return handleError(err)
}
func (cmd *cmdWrapper) Wait() error {
err := (*osexec.Cmd)(cmd).Wait()
return handleError(err)
}
// Run is part of the Cmd interface. // Run is part of the Cmd interface.
func (cmd *cmdWrapper) Run() error { func (cmd *cmdWrapper) Run() error {
err := (*osexec.Cmd)(cmd).Run() err := (*osexec.Cmd)(cmd).Run()
@ -206,10 +241,12 @@ func (e CodeExitError) String() string {
return e.Err.Error() return e.Err.Error()
} }
// Exited is to check if the process has finished
func (e CodeExitError) Exited() bool { func (e CodeExitError) Exited() bool {
return true return true
} }
// ExitStatus is for checking the error code
func (e CodeExitError) ExitStatus() int { func (e CodeExitError) ExitStatus() int {
return e.Code return e.Code
} }

View File

@ -1,6 +1,7 @@
// Copyright 2013 The Go Authors. All rights reserved. // Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package yaml package yaml
import ( import (

View File

@ -4,13 +4,14 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"reflect" "reflect"
"strconv" "strconv"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
) )
// Marshals the object into JSON then converts JSON to YAML and returns the // Marshal marshals the object into JSON then converts JSON to YAML and returns the
// YAML. // YAML.
func Marshal(o interface{}) ([]byte, error) { func Marshal(o interface{}) ([]byte, error) {
j, err := json.Marshal(o) j, err := json.Marshal(o)
@ -26,15 +27,35 @@ func Marshal(o interface{}) ([]byte, error) {
return y, nil return y, nil
} }
// Converts YAML to JSON then uses JSON to unmarshal into an object. // JSONOpt is a decoding option for decoding from JSON format.
func Unmarshal(y []byte, o interface{}) error { type JSONOpt func(*json.Decoder) *json.Decoder
// Unmarshal converts YAML to JSON then uses JSON to unmarshal into an object,
// optionally configuring the behavior of the JSON unmarshal.
func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error {
return yamlUnmarshal(y, o, false, opts...)
}
// UnmarshalStrict strictly converts YAML to JSON then uses JSON to unmarshal
// into an object, optionally configuring the behavior of the JSON unmarshal.
func UnmarshalStrict(y []byte, o interface{}, opts ...JSONOpt) error {
return yamlUnmarshal(y, o, true, append(opts, DisallowUnknownFields)...)
}
// yamlUnmarshal unmarshals the given YAML byte stream into the given interface,
// optionally performing the unmarshalling strictly
func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {
vo := reflect.ValueOf(o) vo := reflect.ValueOf(o)
j, err := yamlToJSON(y, &vo) unmarshalFn := yaml.Unmarshal
if strict {
unmarshalFn = yaml.UnmarshalStrict
}
j, err := yamlToJSON(y, &vo, unmarshalFn)
if err != nil { if err != nil {
return fmt.Errorf("error converting YAML to JSON: %v", err) return fmt.Errorf("error converting YAML to JSON: %v", err)
} }
err = json.Unmarshal(j, o) err = jsonUnmarshal(bytes.NewReader(j), o, opts...)
if err != nil { if err != nil {
return fmt.Errorf("error unmarshaling JSON: %v", err) return fmt.Errorf("error unmarshaling JSON: %v", err)
} }
@ -42,7 +63,22 @@ func Unmarshal(y []byte, o interface{}) error {
return nil return nil
} }
// Convert JSON to YAML. // jsonUnmarshal unmarshals the JSON byte stream from the given reader into the
// object, optionally applying decoder options prior to decoding. We are not
// using json.Unmarshal directly as we want the chance to pass in non-default
// options.
func jsonUnmarshal(r io.Reader, o interface{}, opts ...JSONOpt) error {
d := json.NewDecoder(r)
for _, opt := range opts {
d = opt(d)
}
if err := d.Decode(&o); err != nil {
return fmt.Errorf("while decoding JSON: %v", err)
}
return nil
}
// JSONToYAML Converts JSON to YAML.
func JSONToYAML(j []byte) ([]byte, error) { func JSONToYAML(j []byte) ([]byte, error) {
// Convert the JSON to an object. // Convert the JSON to an object.
var jsonObj interface{} var jsonObj interface{}
@ -60,8 +96,8 @@ func JSONToYAML(j []byte) ([]byte, error) {
return yaml.Marshal(jsonObj) return yaml.Marshal(jsonObj)
} }
// Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through // YAMLToJSON converts YAML to JSON. Since JSON is a subset of YAML,
// this method should be a no-op. // passing JSON through this method should be a no-op.
// //
// Things YAML can do that are not supported by JSON: // Things YAML can do that are not supported by JSON:
// * In YAML you can have binary and null keys in your maps. These are invalid // * In YAML you can have binary and null keys in your maps. These are invalid
@ -70,14 +106,22 @@ func JSONToYAML(j []byte) ([]byte, error) {
// use binary data with this library, encode the data as base64 as usual but do // use binary data with this library, encode the data as base64 as usual but do
// not use the !!binary tag in your YAML. This will ensure the original base64 // not use the !!binary tag in your YAML. This will ensure the original base64
// encoded data makes it all the way through to the JSON. // encoded data makes it all the way through to the JSON.
//
// For strict decoding of YAML, use YAMLToJSONStrict.
func YAMLToJSON(y []byte) ([]byte, error) { func YAMLToJSON(y []byte) ([]byte, error) {
return yamlToJSON(y, nil) return yamlToJSON(y, nil, yaml.Unmarshal)
} }
func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) { // YAMLToJSONStrict is like YAMLToJSON but enables strict YAML decoding,
// returning an error on any duplicate field names.
func YAMLToJSONStrict(y []byte) ([]byte, error) {
return yamlToJSON(y, nil, yaml.UnmarshalStrict)
}
func yamlToJSON(y []byte, jsonTarget *reflect.Value, yamlUnmarshal func([]byte, interface{}) error) ([]byte, error) {
// Convert the YAML to an object. // Convert the YAML to an object.
var yamlObj interface{} var yamlObj interface{}
err := yaml.Unmarshal(y, &yamlObj) err := yamlUnmarshal(y, &yamlObj)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -272,6 +316,4 @@ func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (in
} }
return yamlObj, nil return yamlObj, nil
} }
return nil, nil
} }

14
vendor/sigs.k8s.io/yaml/yaml_go110.go generated vendored Normal file
View File

@ -0,0 +1,14 @@
// This file contains changes that are only compatible with go 1.10 and onwards.
// +build go1.10
package yaml
import "encoding/json"
// DisallowUnknownFields configures the JSON decoder to error out if unknown
// fields come along, instead of dropping them by default.
func DisallowUnknownFields(d *json.Decoder) *json.Decoder {
d.DisallowUnknownFields()
return d
}