repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/genid/name.go
vendor/google.golang.org/protobuf/internal/genid/name.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package genid const ( NoUnkeyedLiteral_goname = "noUnkeyedLiteral" NoUnkeyedLiteralA_goname = "XXX_NoUnkeyedLiteral" BuilderSuffix_goname = "_builder" )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/genid/empty_gen.go
vendor/google.golang.org/protobuf/internal/genid/empty_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_empty_proto = "google/protobuf/empty.proto" // Names for google.protobuf.Empty. const ( Empty_message_name protoreflect.Name = "Empty" Empty_message_fullname protoreflect.FullName = "google.protobuf.Empty" )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/genid/wrappers_gen.go
vendor/google.golang.org/protobuf/internal/genid/wrappers_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_wrappers_proto = "google/protobuf/wrappers.proto" // Names for google.protobuf.DoubleValue. const ( DoubleValue_message_name protoreflect.Name = "DoubleValue" DoubleValue_message_fullname protoreflect.FullName = "google.protobuf.DoubleValue" ) // Field names for google.protobuf.DoubleValue. const ( DoubleValue_Value_field_name protoreflect.Name = "value" DoubleValue_Value_field_fullname protoreflect.FullName = "google.protobuf.DoubleValue.value" ) // Field numbers for google.protobuf.DoubleValue. const ( DoubleValue_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.FloatValue. const ( FloatValue_message_name protoreflect.Name = "FloatValue" FloatValue_message_fullname protoreflect.FullName = "google.protobuf.FloatValue" ) // Field names for google.protobuf.FloatValue. const ( FloatValue_Value_field_name protoreflect.Name = "value" FloatValue_Value_field_fullname protoreflect.FullName = "google.protobuf.FloatValue.value" ) // Field numbers for google.protobuf.FloatValue. const ( FloatValue_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.Int64Value. const ( Int64Value_message_name protoreflect.Name = "Int64Value" Int64Value_message_fullname protoreflect.FullName = "google.protobuf.Int64Value" ) // Field names for google.protobuf.Int64Value. const ( Int64Value_Value_field_name protoreflect.Name = "value" Int64Value_Value_field_fullname protoreflect.FullName = "google.protobuf.Int64Value.value" ) // Field numbers for google.protobuf.Int64Value. const ( Int64Value_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.UInt64Value. const ( UInt64Value_message_name protoreflect.Name = "UInt64Value" UInt64Value_message_fullname protoreflect.FullName = "google.protobuf.UInt64Value" ) // Field names for google.protobuf.UInt64Value. const ( UInt64Value_Value_field_name protoreflect.Name = "value" UInt64Value_Value_field_fullname protoreflect.FullName = "google.protobuf.UInt64Value.value" ) // Field numbers for google.protobuf.UInt64Value. const ( UInt64Value_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.Int32Value. const ( Int32Value_message_name protoreflect.Name = "Int32Value" Int32Value_message_fullname protoreflect.FullName = "google.protobuf.Int32Value" ) // Field names for google.protobuf.Int32Value. const ( Int32Value_Value_field_name protoreflect.Name = "value" Int32Value_Value_field_fullname protoreflect.FullName = "google.protobuf.Int32Value.value" ) // Field numbers for google.protobuf.Int32Value. const ( Int32Value_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.UInt32Value. const ( UInt32Value_message_name protoreflect.Name = "UInt32Value" UInt32Value_message_fullname protoreflect.FullName = "google.protobuf.UInt32Value" ) // Field names for google.protobuf.UInt32Value. const ( UInt32Value_Value_field_name protoreflect.Name = "value" UInt32Value_Value_field_fullname protoreflect.FullName = "google.protobuf.UInt32Value.value" ) // Field numbers for google.protobuf.UInt32Value. const ( UInt32Value_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.BoolValue. const ( BoolValue_message_name protoreflect.Name = "BoolValue" BoolValue_message_fullname protoreflect.FullName = "google.protobuf.BoolValue" ) // Field names for google.protobuf.BoolValue. const ( BoolValue_Value_field_name protoreflect.Name = "value" BoolValue_Value_field_fullname protoreflect.FullName = "google.protobuf.BoolValue.value" ) // Field numbers for google.protobuf.BoolValue. const ( BoolValue_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.StringValue. const ( StringValue_message_name protoreflect.Name = "StringValue" StringValue_message_fullname protoreflect.FullName = "google.protobuf.StringValue" ) // Field names for google.protobuf.StringValue. const ( StringValue_Value_field_name protoreflect.Name = "value" StringValue_Value_field_fullname protoreflect.FullName = "google.protobuf.StringValue.value" ) // Field numbers for google.protobuf.StringValue. const ( StringValue_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.BytesValue. const ( BytesValue_message_name protoreflect.Name = "BytesValue" BytesValue_message_fullname protoreflect.FullName = "google.protobuf.BytesValue" ) // Field names for google.protobuf.BytesValue. const ( BytesValue_Value_field_name protoreflect.Name = "value" BytesValue_Value_field_fullname protoreflect.FullName = "google.protobuf.BytesValue.value" ) // Field numbers for google.protobuf.BytesValue. const ( BytesValue_Value_field_number protoreflect.FieldNumber = 1 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/genid/source_context_gen.go
vendor/google.golang.org/protobuf/internal/genid/source_context_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_source_context_proto = "google/protobuf/source_context.proto" // Names for google.protobuf.SourceContext. const ( SourceContext_message_name protoreflect.Name = "SourceContext" SourceContext_message_fullname protoreflect.FullName = "google.protobuf.SourceContext" ) // Field names for google.protobuf.SourceContext. const ( SourceContext_FileName_field_name protoreflect.Name = "file_name" SourceContext_FileName_field_fullname protoreflect.FullName = "google.protobuf.SourceContext.file_name" ) // Field numbers for google.protobuf.SourceContext. const ( SourceContext_FileName_field_number protoreflect.FieldNumber = 1 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/genid/doc.go
vendor/google.golang.org/protobuf/internal/genid/doc.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package genid contains constants for declarations in descriptor.proto // and the well-known types. package genid import "google.golang.org/protobuf/reflect/protoreflect" const GoogleProtobuf_package protoreflect.FullName = "google.protobuf"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/genid/api_gen.go
vendor/google.golang.org/protobuf/internal/genid/api_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_api_proto = "google/protobuf/api.proto" // Names for google.protobuf.Api. const ( Api_message_name protoreflect.Name = "Api" Api_message_fullname protoreflect.FullName = "google.protobuf.Api" ) // Field names for google.protobuf.Api. const ( Api_Name_field_name protoreflect.Name = "name" Api_Methods_field_name protoreflect.Name = "methods" Api_Options_field_name protoreflect.Name = "options" Api_Version_field_name protoreflect.Name = "version" Api_SourceContext_field_name protoreflect.Name = "source_context" Api_Mixins_field_name protoreflect.Name = "mixins" Api_Syntax_field_name protoreflect.Name = "syntax" Api_Name_field_fullname protoreflect.FullName = "google.protobuf.Api.name" Api_Methods_field_fullname protoreflect.FullName = "google.protobuf.Api.methods" Api_Options_field_fullname protoreflect.FullName = "google.protobuf.Api.options" Api_Version_field_fullname protoreflect.FullName = "google.protobuf.Api.version" Api_SourceContext_field_fullname protoreflect.FullName = "google.protobuf.Api.source_context" Api_Mixins_field_fullname protoreflect.FullName = "google.protobuf.Api.mixins" Api_Syntax_field_fullname protoreflect.FullName = "google.protobuf.Api.syntax" ) // Field numbers for google.protobuf.Api. const ( Api_Name_field_number protoreflect.FieldNumber = 1 Api_Methods_field_number protoreflect.FieldNumber = 2 Api_Options_field_number protoreflect.FieldNumber = 3 Api_Version_field_number protoreflect.FieldNumber = 4 Api_SourceContext_field_number protoreflect.FieldNumber = 5 Api_Mixins_field_number protoreflect.FieldNumber = 6 Api_Syntax_field_number protoreflect.FieldNumber = 7 ) // Names for google.protobuf.Method. const ( Method_message_name protoreflect.Name = "Method" Method_message_fullname protoreflect.FullName = "google.protobuf.Method" ) // Field names for google.protobuf.Method. const ( Method_Name_field_name protoreflect.Name = "name" Method_RequestTypeUrl_field_name protoreflect.Name = "request_type_url" Method_RequestStreaming_field_name protoreflect.Name = "request_streaming" Method_ResponseTypeUrl_field_name protoreflect.Name = "response_type_url" Method_ResponseStreaming_field_name protoreflect.Name = "response_streaming" Method_Options_field_name protoreflect.Name = "options" Method_Syntax_field_name protoreflect.Name = "syntax" Method_Name_field_fullname protoreflect.FullName = "google.protobuf.Method.name" Method_RequestTypeUrl_field_fullname protoreflect.FullName = "google.protobuf.Method.request_type_url" Method_RequestStreaming_field_fullname protoreflect.FullName = "google.protobuf.Method.request_streaming" Method_ResponseTypeUrl_field_fullname protoreflect.FullName = "google.protobuf.Method.response_type_url" Method_ResponseStreaming_field_fullname protoreflect.FullName = "google.protobuf.Method.response_streaming" Method_Options_field_fullname protoreflect.FullName = "google.protobuf.Method.options" Method_Syntax_field_fullname protoreflect.FullName = "google.protobuf.Method.syntax" ) // Field numbers for google.protobuf.Method. const ( Method_Name_field_number protoreflect.FieldNumber = 1 Method_RequestTypeUrl_field_number protoreflect.FieldNumber = 2 Method_RequestStreaming_field_number protoreflect.FieldNumber = 3 Method_ResponseTypeUrl_field_number protoreflect.FieldNumber = 4 Method_ResponseStreaming_field_number protoreflect.FieldNumber = 5 Method_Options_field_number protoreflect.FieldNumber = 6 Method_Syntax_field_number protoreflect.FieldNumber = 7 ) // Names for google.protobuf.Mixin. const ( Mixin_message_name protoreflect.Name = "Mixin" Mixin_message_fullname protoreflect.FullName = "google.protobuf.Mixin" ) // Field names for google.protobuf.Mixin. const ( Mixin_Name_field_name protoreflect.Name = "name" Mixin_Root_field_name protoreflect.Name = "root" Mixin_Name_field_fullname protoreflect.FullName = "google.protobuf.Mixin.name" Mixin_Root_field_fullname protoreflect.FullName = "google.protobuf.Mixin.root" ) // Field numbers for google.protobuf.Mixin. const ( Mixin_Name_field_number protoreflect.FieldNumber = 1 Mixin_Root_field_number protoreflect.FieldNumber = 2 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/genid/wrappers.go
vendor/google.golang.org/protobuf/internal/genid/wrappers.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package genid import "google.golang.org/protobuf/reflect/protoreflect" // Generic field name and number for messages in wrappers.proto. const ( WrapperValue_Value_field_name protoreflect.Name = "value" WrapperValue_Value_field_number protoreflect.FieldNumber = 1 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/genid/timestamp_gen.go
vendor/google.golang.org/protobuf/internal/genid/timestamp_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_timestamp_proto = "google/protobuf/timestamp.proto" // Names for google.protobuf.Timestamp. const ( Timestamp_message_name protoreflect.Name = "Timestamp" Timestamp_message_fullname protoreflect.FullName = "google.protobuf.Timestamp" ) // Field names for google.protobuf.Timestamp. const ( Timestamp_Seconds_field_name protoreflect.Name = "seconds" Timestamp_Nanos_field_name protoreflect.Name = "nanos" Timestamp_Seconds_field_fullname protoreflect.FullName = "google.protobuf.Timestamp.seconds" Timestamp_Nanos_field_fullname protoreflect.FullName = "google.protobuf.Timestamp.nanos" ) // Field numbers for google.protobuf.Timestamp. const ( Timestamp_Seconds_field_number protoreflect.FieldNumber = 1 Timestamp_Nanos_field_number protoreflect.FieldNumber = 2 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/genid/struct_gen.go
vendor/google.golang.org/protobuf/internal/genid/struct_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_struct_proto = "google/protobuf/struct.proto" // Full and short names for google.protobuf.NullValue. const ( NullValue_enum_fullname = "google.protobuf.NullValue" NullValue_enum_name = "NullValue" ) // Enum values for google.protobuf.NullValue. const ( NullValue_NULL_VALUE_enum_value = 0 ) // Names for google.protobuf.Struct. const ( Struct_message_name protoreflect.Name = "Struct" Struct_message_fullname protoreflect.FullName = "google.protobuf.Struct" ) // Field names for google.protobuf.Struct. const ( Struct_Fields_field_name protoreflect.Name = "fields" Struct_Fields_field_fullname protoreflect.FullName = "google.protobuf.Struct.fields" ) // Field numbers for google.protobuf.Struct. const ( Struct_Fields_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.Struct.FieldsEntry. const ( Struct_FieldsEntry_message_name protoreflect.Name = "FieldsEntry" Struct_FieldsEntry_message_fullname protoreflect.FullName = "google.protobuf.Struct.FieldsEntry" ) // Field names for google.protobuf.Struct.FieldsEntry. const ( Struct_FieldsEntry_Key_field_name protoreflect.Name = "key" Struct_FieldsEntry_Value_field_name protoreflect.Name = "value" Struct_FieldsEntry_Key_field_fullname protoreflect.FullName = "google.protobuf.Struct.FieldsEntry.key" Struct_FieldsEntry_Value_field_fullname protoreflect.FullName = "google.protobuf.Struct.FieldsEntry.value" ) // Field numbers for google.protobuf.Struct.FieldsEntry. const ( Struct_FieldsEntry_Key_field_number protoreflect.FieldNumber = 1 Struct_FieldsEntry_Value_field_number protoreflect.FieldNumber = 2 ) // Names for google.protobuf.Value. const ( Value_message_name protoreflect.Name = "Value" Value_message_fullname protoreflect.FullName = "google.protobuf.Value" ) // Field names for google.protobuf.Value. const ( Value_NullValue_field_name protoreflect.Name = "null_value" Value_NumberValue_field_name protoreflect.Name = "number_value" Value_StringValue_field_name protoreflect.Name = "string_value" Value_BoolValue_field_name protoreflect.Name = "bool_value" Value_StructValue_field_name protoreflect.Name = "struct_value" Value_ListValue_field_name protoreflect.Name = "list_value" Value_NullValue_field_fullname protoreflect.FullName = "google.protobuf.Value.null_value" Value_NumberValue_field_fullname protoreflect.FullName = "google.protobuf.Value.number_value" Value_StringValue_field_fullname protoreflect.FullName = "google.protobuf.Value.string_value" Value_BoolValue_field_fullname protoreflect.FullName = "google.protobuf.Value.bool_value" Value_StructValue_field_fullname protoreflect.FullName = "google.protobuf.Value.struct_value" Value_ListValue_field_fullname protoreflect.FullName = "google.protobuf.Value.list_value" ) // Field numbers for google.protobuf.Value. const ( Value_NullValue_field_number protoreflect.FieldNumber = 1 Value_NumberValue_field_number protoreflect.FieldNumber = 2 Value_StringValue_field_number protoreflect.FieldNumber = 3 Value_BoolValue_field_number protoreflect.FieldNumber = 4 Value_StructValue_field_number protoreflect.FieldNumber = 5 Value_ListValue_field_number protoreflect.FieldNumber = 6 ) // Oneof names for google.protobuf.Value. const ( Value_Kind_oneof_name protoreflect.Name = "kind" Value_Kind_oneof_fullname protoreflect.FullName = "google.protobuf.Value.kind" ) // Names for google.protobuf.ListValue. const ( ListValue_message_name protoreflect.Name = "ListValue" ListValue_message_fullname protoreflect.FullName = "google.protobuf.ListValue" ) // Field names for google.protobuf.ListValue. const ( ListValue_Values_field_name protoreflect.Name = "values" ListValue_Values_field_fullname protoreflect.FullName = "google.protobuf.ListValue.values" ) // Field numbers for google.protobuf.ListValue. const ( ListValue_Values_field_number protoreflect.FieldNumber = 1 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/editionssupport/editions.go
vendor/google.golang.org/protobuf/internal/editionssupport/editions.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package editionssupport defines constants for editions that are supported. package editionssupport import "google.golang.org/protobuf/types/descriptorpb" const ( Minimum = descriptorpb.Edition_EDITION_PROTO2 Maximum = descriptorpb.Edition_EDITION_2023 // MaximumKnown is the maximum edition that is known to Go Protobuf, but not // declared as supported. In other words: end users cannot use it, but // testprotos inside Go Protobuf can. MaximumKnown = descriptorpb.Edition_EDITION_2024 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/descopts/options.go
vendor/google.golang.org/protobuf/internal/descopts/options.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package descopts contains the nil pointers to concrete descriptor options. // // This package exists as a form of reverse dependency injection so that certain // packages (e.g., internal/filedesc and internal/filetype can avoid a direct // dependency on the descriptor proto package). package descopts import "google.golang.org/protobuf/reflect/protoreflect" // These variables are set by the init function in descriptor.pb.go via logic // in internal/filetype. In other words, so long as the descriptor proto package // is linked in, these variables will be populated. // // Each variable is populated with a nil pointer to the options struct. var ( File protoreflect.ProtoMessage Enum protoreflect.ProtoMessage EnumValue protoreflect.ProtoMessage Message protoreflect.ProtoMessage Field protoreflect.ProtoMessage Oneof protoreflect.ProtoMessage ExtensionRange protoreflect.ProtoMessage Service protoreflect.ProtoMessage Method protoreflect.ProtoMessage )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/google.golang.org/protobuf/internal/set/ints.go
vendor/google.golang.org/protobuf/internal/set/ints.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package set provides simple set data structures for uint64s. package set import "math/bits" // int64s represents a set of integers within the range of 0..63. type int64s uint64 func (bs *int64s) Len() int { return bits.OnesCount64(uint64(*bs)) } func (bs *int64s) Has(n uint64) bool { return uint64(*bs)&(uint64(1)<<n) > 0 } func (bs *int64s) Set(n uint64) { *(*uint64)(bs) |= uint64(1) << n } func (bs *int64s) Clear(n uint64) { *(*uint64)(bs) &^= uint64(1) << n } // Ints represents a set of integers within the range of 0..math.MaxUint64. type Ints struct { lo int64s hi map[uint64]struct{} } func (bs *Ints) Len() int { return bs.lo.Len() + len(bs.hi) } func (bs *Ints) Has(n uint64) bool { if n < 64 { return bs.lo.Has(n) } _, ok := bs.hi[n] return ok } func (bs *Ints) Set(n uint64) { if n < 64 { bs.lo.Set(n) return } if bs.hi == nil { bs.hi = make(map[uint64]struct{}) } bs.hi[n] = struct{}{} } func (bs *Ints) Clear(n uint64) { if n < 64 { bs.lo.Clear(n) return } delete(bs.hi, n) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/dario.cat/mergo/merge.go
vendor/dario.cat/mergo/merge.go
// Copyright 2013 Dario Castañé. All rights reserved. // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Based on src/pkg/reflect/deepequal.go from official // golang's stdlib. package mergo import ( "fmt" "reflect" ) func hasMergeableFields(dst reflect.Value) (exported bool) { for i, n := 0, dst.NumField(); i < n; i++ { field := dst.Type().Field(i) if field.Anonymous && dst.Field(i).Kind() == reflect.Struct { exported = exported || hasMergeableFields(dst.Field(i)) } else if isExportedComponent(&field) { exported = exported || len(field.PkgPath) == 0 } } return } func isExportedComponent(field *reflect.StructField) bool { pkgPath := field.PkgPath if len(pkgPath) > 0 { return false } c := field.Name[0] if 'a' <= c && c <= 'z' || c == '_' { return false } return true } type Config struct { Transformers Transformers Overwrite bool ShouldNotDereference bool AppendSlice bool TypeCheck bool overwriteWithEmptyValue bool overwriteSliceWithEmptyValue bool sliceDeepCopy bool debug bool } type Transformers interface { Transformer(reflect.Type) func(dst, src reflect.Value) error } // Traverses recursively both values, assigning src's fields values to dst. // The map argument tracks comparisons that have already been seen, which allows // short circuiting on recursive types. func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { overwrite := config.Overwrite typeCheck := config.TypeCheck overwriteWithEmptySrc := config.overwriteWithEmptyValue overwriteSliceWithEmptySrc := config.overwriteSliceWithEmptyValue sliceDeepCopy := config.sliceDeepCopy if !src.IsValid() { return } if dst.CanAddr() { addr := dst.UnsafeAddr() h := 17 * addr seen := visited[h] typ := dst.Type() for p := seen; p != nil; p = p.next { if p.ptr == addr && p.typ == typ { return nil } } // Remember, remember... visited[h] = &visit{typ, seen, addr} } if config.Transformers != nil && !isReflectNil(dst) && dst.IsValid() { if fn := config.Transformers.Transformer(dst.Type()); fn != nil { err = fn(dst, src) return } } switch dst.Kind() { case reflect.Struct: if hasMergeableFields(dst) { for i, n := 0, dst.NumField(); i < n; i++ { if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, config); err != nil { return } } } else { if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) { dst.Set(src) } } case reflect.Map: if dst.IsNil() && !src.IsNil() { if dst.CanSet() { dst.Set(reflect.MakeMap(dst.Type())) } else { dst = src return } } if src.Kind() != reflect.Map { if overwrite && dst.CanSet() { dst.Set(src) } return } for _, key := range src.MapKeys() { srcElement := src.MapIndex(key) if !srcElement.IsValid() { continue } dstElement := dst.MapIndex(key) switch srcElement.Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice: if srcElement.IsNil() { if overwrite { dst.SetMapIndex(key, srcElement) } continue } fallthrough default: if !srcElement.CanInterface() { continue } switch reflect.TypeOf(srcElement.Interface()).Kind() { case reflect.Struct: fallthrough case reflect.Ptr: fallthrough case reflect.Map: srcMapElm := srcElement dstMapElm := dstElement if srcMapElm.CanInterface() { srcMapElm = reflect.ValueOf(srcMapElm.Interface()) if dstMapElm.IsValid() { dstMapElm = reflect.ValueOf(dstMapElm.Interface()) } } if err = deepMerge(dstMapElm, srcMapElm, visited, depth+1, config); err != nil { return } case reflect.Slice: srcSlice := reflect.ValueOf(srcElement.Interface()) var dstSlice reflect.Value if !dstElement.IsValid() || dstElement.IsNil() { dstSlice = reflect.MakeSlice(srcSlice.Type(), 0, srcSlice.Len()) } else { dstSlice = reflect.ValueOf(dstElement.Interface()) } if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy { if typeCheck && srcSlice.Type() != dstSlice.Type() { return fmt.Errorf("cannot override two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) } dstSlice = srcSlice } else if config.AppendSlice { if srcSlice.Type() != dstSlice.Type() { return fmt.Errorf("cannot append two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) } dstSlice = reflect.AppendSlice(dstSlice, srcSlice) } else if sliceDeepCopy { i := 0 for ; i < srcSlice.Len() && i < dstSlice.Len(); i++ { srcElement := srcSlice.Index(i) dstElement := dstSlice.Index(i) if srcElement.CanInterface() { srcElement = reflect.ValueOf(srcElement.Interface()) } if dstElement.CanInterface() { dstElement = reflect.ValueOf(dstElement.Interface()) } if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { return } } } dst.SetMapIndex(key, dstSlice) } } if dstElement.IsValid() && !isEmptyValue(dstElement, !config.ShouldNotDereference) { if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice { continue } if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map && reflect.TypeOf(dstElement.Interface()).Kind() == reflect.Map { continue } } if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement, !config.ShouldNotDereference)) { if dst.IsNil() { dst.Set(reflect.MakeMap(dst.Type())) } dst.SetMapIndex(key, srcElement) } } // Ensure that all keys in dst are deleted if they are not in src. if overwriteWithEmptySrc { for _, key := range dst.MapKeys() { srcElement := src.MapIndex(key) if !srcElement.IsValid() { dst.SetMapIndex(key, reflect.Value{}) } } } case reflect.Slice: if !dst.CanSet() { break } if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy { dst.Set(src) } else if config.AppendSlice { if src.Type() != dst.Type() { return fmt.Errorf("cannot append two slice with different type (%s, %s)", src.Type(), dst.Type()) } dst.Set(reflect.AppendSlice(dst, src)) } else if sliceDeepCopy { for i := 0; i < src.Len() && i < dst.Len(); i++ { srcElement := src.Index(i) dstElement := dst.Index(i) if srcElement.CanInterface() { srcElement = reflect.ValueOf(srcElement.Interface()) } if dstElement.CanInterface() { dstElement = reflect.ValueOf(dstElement.Interface()) } if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { return } } } case reflect.Ptr: fallthrough case reflect.Interface: if isReflectNil(src) { if overwriteWithEmptySrc && dst.CanSet() && src.Type().AssignableTo(dst.Type()) { dst.Set(src) } break } if src.Kind() != reflect.Interface { if dst.IsNil() || (src.Kind() != reflect.Ptr && overwrite) { if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) { dst.Set(src) } } else if src.Kind() == reflect.Ptr { if !config.ShouldNotDereference { if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { return } } else if src.Elem().Kind() != reflect.Struct { if overwriteWithEmptySrc || (overwrite && !src.IsNil()) || dst.IsNil() { dst.Set(src) } } } else if dst.Elem().Type() == src.Type() { if err = deepMerge(dst.Elem(), src, visited, depth+1, config); err != nil { return } } else { return ErrDifferentArgumentsTypes } break } if dst.IsNil() || overwrite { if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) { dst.Set(src) } break } if dst.Elem().Kind() == src.Elem().Kind() { if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { return } break } default: mustSet := (isEmptyValue(dst, !config.ShouldNotDereference) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) if mustSet { if dst.CanSet() { dst.Set(src) } else { dst = src } } } return } // Merge will fill any empty for value type attributes on the dst struct using corresponding // src attributes if they themselves are not empty. dst and src must be valid same-type structs // and dst must be a pointer to struct. // It won't merge unexported (private) fields and will do recursively any exported field. func Merge(dst, src interface{}, opts ...func(*Config)) error { return merge(dst, src, opts...) } // MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overridden by // non-empty src attribute values. // Deprecated: use Merge(…) with WithOverride func MergeWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { return merge(dst, src, append(opts, WithOverride)...) } // WithTransformers adds transformers to merge, allowing to customize the merging of some types. func WithTransformers(transformers Transformers) func(*Config) { return func(config *Config) { config.Transformers = transformers } } // WithOverride will make merge override non-empty dst attributes with non-empty src attributes values. func WithOverride(config *Config) { config.Overwrite = true } // WithOverwriteWithEmptyValue will make merge override non empty dst attributes with empty src attributes values. func WithOverwriteWithEmptyValue(config *Config) { config.Overwrite = true config.overwriteWithEmptyValue = true } // WithOverrideEmptySlice will make merge override empty dst slice with empty src slice. func WithOverrideEmptySlice(config *Config) { config.overwriteSliceWithEmptyValue = true } // WithoutDereference prevents dereferencing pointers when evaluating whether they are empty // (i.e. a non-nil pointer is never considered empty). func WithoutDereference(config *Config) { config.ShouldNotDereference = true } // WithAppendSlice will make merge append slices instead of overwriting it. func WithAppendSlice(config *Config) { config.AppendSlice = true } // WithTypeCheck will make merge check types while overwriting it (must be used with WithOverride). func WithTypeCheck(config *Config) { config.TypeCheck = true } // WithSliceDeepCopy will merge slice element one by one with Overwrite flag. func WithSliceDeepCopy(config *Config) { config.sliceDeepCopy = true config.Overwrite = true } func merge(dst, src interface{}, opts ...func(*Config)) error { if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { return ErrNonPointerArgument } var ( vDst, vSrc reflect.Value err error ) config := &Config{} for _, opt := range opts { opt(config) } if vDst, vSrc, err = resolveValues(dst, src); err != nil { return err } if vDst.Type() != vSrc.Type() { return ErrDifferentArgumentsTypes } return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) } // IsReflectNil is the reflect value provided nil func isReflectNil(v reflect.Value) bool { k := v.Kind() switch k { case reflect.Interface, reflect.Slice, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr: // Both interface and slice are nil if first word is 0. // Both are always bigger than a word; assume flagIndir. return v.IsNil() default: return false } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/dario.cat/mergo/map.go
vendor/dario.cat/mergo/map.go
// Copyright 2014 Dario Castañé. All rights reserved. // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Based on src/pkg/reflect/deepequal.go from official // golang's stdlib. package mergo import ( "fmt" "reflect" "unicode" "unicode/utf8" ) func changeInitialCase(s string, mapper func(rune) rune) string { if s == "" { return s } r, n := utf8.DecodeRuneInString(s) return string(mapper(r)) + s[n:] } func isExported(field reflect.StructField) bool { r, _ := utf8.DecodeRuneInString(field.Name) return r >= 'A' && r <= 'Z' } // Traverses recursively both values, assigning src's fields values to dst. // The map argument tracks comparisons that have already been seen, which allows // short circuiting on recursive types. func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { overwrite := config.Overwrite if dst.CanAddr() { addr := dst.UnsafeAddr() h := 17 * addr seen := visited[h] typ := dst.Type() for p := seen; p != nil; p = p.next { if p.ptr == addr && p.typ == typ { return nil } } // Remember, remember... visited[h] = &visit{typ, seen, addr} } zeroValue := reflect.Value{} switch dst.Kind() { case reflect.Map: dstMap := dst.Interface().(map[string]interface{}) for i, n := 0, src.NumField(); i < n; i++ { srcType := src.Type() field := srcType.Field(i) if !isExported(field) { continue } fieldName := field.Name fieldName = changeInitialCase(fieldName, unicode.ToLower) if _, ok := dstMap[fieldName]; !ok || (!isEmptyValue(reflect.ValueOf(src.Field(i).Interface()), !config.ShouldNotDereference) && overwrite) || config.overwriteWithEmptyValue { dstMap[fieldName] = src.Field(i).Interface() } } case reflect.Ptr: if dst.IsNil() { v := reflect.New(dst.Type().Elem()) dst.Set(v) } dst = dst.Elem() fallthrough case reflect.Struct: srcMap := src.Interface().(map[string]interface{}) for key := range srcMap { config.overwriteWithEmptyValue = true srcValue := srcMap[key] fieldName := changeInitialCase(key, unicode.ToUpper) dstElement := dst.FieldByName(fieldName) if dstElement == zeroValue { // We discard it because the field doesn't exist. continue } srcElement := reflect.ValueOf(srcValue) dstKind := dstElement.Kind() srcKind := srcElement.Kind() if srcKind == reflect.Ptr && dstKind != reflect.Ptr { srcElement = srcElement.Elem() srcKind = reflect.TypeOf(srcElement.Interface()).Kind() } else if dstKind == reflect.Ptr { // Can this work? I guess it can't. if srcKind != reflect.Ptr && srcElement.CanAddr() { srcPtr := srcElement.Addr() srcElement = reflect.ValueOf(srcPtr) srcKind = reflect.Ptr } } if !srcElement.IsValid() { continue } if srcKind == dstKind { if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { return } } else if dstKind == reflect.Interface && dstElement.Kind() == reflect.Interface { if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { return } } else if srcKind == reflect.Map { if err = deepMap(dstElement, srcElement, visited, depth+1, config); err != nil { return } } else { return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind) } } } return } // Map sets fields' values in dst from src. // src can be a map with string keys or a struct. dst must be the opposite: // if src is a map, dst must be a valid pointer to struct. If src is a struct, // dst must be map[string]interface{}. // It won't merge unexported (private) fields and will do recursively // any exported field. // If dst is a map, keys will be src fields' names in lower camel case. // Missing key in src that doesn't match a field in dst will be skipped. This // doesn't apply if dst is a map. // This is separated method from Merge because it is cleaner and it keeps sane // semantics: merging equal types, mapping different (restricted) types. func Map(dst, src interface{}, opts ...func(*Config)) error { return _map(dst, src, opts...) } // MapWithOverwrite will do the same as Map except that non-empty dst attributes will be overridden by // non-empty src attribute values. // Deprecated: Use Map(…) with WithOverride func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { return _map(dst, src, append(opts, WithOverride)...) } func _map(dst, src interface{}, opts ...func(*Config)) error { if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { return ErrNonPointerArgument } var ( vDst, vSrc reflect.Value err error ) config := &Config{} for _, opt := range opts { opt(config) } if vDst, vSrc, err = resolveValues(dst, src); err != nil { return err } // To be friction-less, we redirect equal-type arguments // to deepMerge. Only because arguments can be anything. if vSrc.Kind() == vDst.Kind() { return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) } switch vSrc.Kind() { case reflect.Struct: if vDst.Kind() != reflect.Map { return ErrExpectedMapAsDestination } case reflect.Map: if vDst.Kind() != reflect.Struct { return ErrExpectedStructAsDestination } default: return ErrNotSupported } return deepMap(vDst, vSrc, make(map[uintptr]*visit), 0, config) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/dario.cat/mergo/mergo.go
vendor/dario.cat/mergo/mergo.go
// Copyright 2013 Dario Castañé. All rights reserved. // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Based on src/pkg/reflect/deepequal.go from official // golang's stdlib. package mergo import ( "errors" "reflect" ) // Errors reported by Mergo when it finds invalid arguments. var ( ErrNilArguments = errors.New("src and dst must not be nil") ErrDifferentArgumentsTypes = errors.New("src and dst must be of same type") ErrNotSupported = errors.New("only structs, maps, and slices are supported") ErrExpectedMapAsDestination = errors.New("dst was expected to be a map") ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct") ErrNonPointerArgument = errors.New("dst must be a pointer") ) // During deepMerge, must keep track of checks that are // in progress. The comparison algorithm assumes that all // checks in progress are true when it reencounters them. // Visited are stored in a map indexed by 17 * a1 + a2; type visit struct { typ reflect.Type next *visit ptr uintptr } // From src/pkg/encoding/json/encode.go. func isEmptyValue(v reflect.Value, shouldDereference bool) bool { switch v.Kind() { case reflect.Array, reflect.Map, reflect.Slice, reflect.String: return v.Len() == 0 case reflect.Bool: return !v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.Interface, reflect.Ptr: if v.IsNil() { return true } if shouldDereference { return isEmptyValue(v.Elem(), shouldDereference) } return false case reflect.Func: return v.IsNil() case reflect.Invalid: return true } return false } func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) { if dst == nil || src == nil { err = ErrNilArguments return } vDst = reflect.ValueOf(dst).Elem() if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map && vDst.Kind() != reflect.Slice { err = ErrNotSupported return } vSrc = reflect.ValueOf(src) // We check if vSrc is a pointer to dereference it. if vSrc.Kind() == reflect.Ptr { vSrc = vSrc.Elem() } return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/dario.cat/mergo/doc.go
vendor/dario.cat/mergo/doc.go
// Copyright 2013 Dario Castañé. All rights reserved. // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). # Status It is ready for production use. It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc. # Important notes 1.0.0 In 1.0.0 Mergo moves to a vanity URL `dario.cat/mergo`. 0.3.9 Please keep in mind that a problematic PR broke 0.3.9. We reverted it in 0.3.10. We consider 0.3.10 as stable but not bug-free. . Also, this version adds suppot for go modules. Keep in mind that in 0.3.2, Mergo changed Merge() and Map() signatures to support transformers. We added an optional/variadic argument so that it won't break the existing code. If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with go get -u dario.cat/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0). # Install Do your usual installation procedure: go get dario.cat/mergo // use in your .go code import ( "dario.cat/mergo" ) # Usage You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as they are zero values too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). if err := mergo.Merge(&dst, src); err != nil { // ... } Also, you can merge overwriting values using the transformer WithOverride. if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil { // ... } Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field. if err := mergo.Map(&dst, srcMap); err != nil { // ... } Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values. Here is a nice example: package main import ( "fmt" "dario.cat/mergo" ) type Foo struct { A string B int64 } func main() { src := Foo{ A: "one", B: 2, } dest := Foo{ A: "two", } mergo.Merge(&dest, src) fmt.Println(dest) // Will print // {two 2} } # Transformers Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, time.Time is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero time.Time? package main import ( "fmt" "dario.cat/mergo" "reflect" "time" ) type timeTransformer struct { } func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { if typ == reflect.TypeOf(time.Time{}) { return func(dst, src reflect.Value) error { if dst.CanSet() { isZero := dst.MethodByName("IsZero") result := isZero.Call([]reflect.Value{}) if result[0].Bool() { dst.Set(src) } } return nil } } return nil } type Snapshot struct { Time time.Time // ... } func main() { src := Snapshot{time.Now()} dest := Snapshot{} mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) fmt.Println(dest) // Will print // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } } # Contact me If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): https://twitter.com/im_dario # About Written by Dario Castañé: https://da.rio.hn # License BSD 3-Clause license, as Go language. */ package mergo
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/codes/doc.go
vendor/go.opentelemetry.io/otel/codes/doc.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 /* Package codes defines the canonical error codes used by OpenTelemetry. It conforms to [the OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/trace/api.md#set-status). */ package codes // import "go.opentelemetry.io/otel/codes"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/codes/codes.go
vendor/go.opentelemetry.io/otel/codes/codes.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package codes // import "go.opentelemetry.io/otel/codes" import ( "encoding/json" "fmt" "strconv" ) const ( // Unset is the default status code. Unset Code = 0 // Error indicates the operation contains an error. // // NOTE: The error code in OTLP is 2. // The value of this enum is only relevant to the internals // of the Go SDK. Error Code = 1 // Ok indicates operation has been validated by an Application developers // or Operator to have completed successfully, or contain no error. // // NOTE: The Ok code in OTLP is 1. // The value of this enum is only relevant to the internals // of the Go SDK. Ok Code = 2 maxCode = 3 ) // Code is an 32-bit representation of a status state. type Code uint32 var codeToStr = map[Code]string{ Unset: "Unset", Error: "Error", Ok: "Ok", } var strToCode = map[string]Code{ `"Unset"`: Unset, `"Error"`: Error, `"Ok"`: Ok, } // String returns the Code as a string. func (c Code) String() string { return codeToStr[c] } // UnmarshalJSON unmarshals b into the Code. // // This is based on the functionality in the gRPC codes package: // https://github.com/grpc/grpc-go/blob/bb64fee312b46ebee26be43364a7a966033521b1/codes/codes.go#L218-L244 func (c *Code) UnmarshalJSON(b []byte) error { // From json.Unmarshaler: By convention, to approximate the behavior of // Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as // a no-op. if string(b) == "null" { return nil } if c == nil { return fmt.Errorf("nil receiver passed to UnmarshalJSON") } var x interface{} if err := json.Unmarshal(b, &x); err != nil { return err } switch x.(type) { case string: if jc, ok := strToCode[string(b)]; ok { *c = jc return nil } return fmt.Errorf("invalid code: %q", string(b)) case float64: if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil { if ci >= maxCode { return fmt.Errorf("invalid code: %q", ci) } *c = Code(ci) return nil } return fmt.Errorf("invalid code: %q", string(b)) default: return fmt.Errorf("invalid code: %q", string(b)) } } // MarshalJSON returns c as the JSON encoding of c. func (c *Code) MarshalJSON() ([]byte, error) { if c == nil { return []byte("null"), nil } str, ok := codeToStr[*c] if !ok { return nil, fmt.Errorf("invalid code: %d", *c) } return []byte(fmt.Sprintf("%q", str)), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/trace/config.go
vendor/go.opentelemetry.io/otel/trace/config.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package trace // import "go.opentelemetry.io/otel/trace" import ( "time" "go.opentelemetry.io/otel/attribute" ) // TracerConfig is a group of options for a Tracer. type TracerConfig struct { instrumentationVersion string // Schema URL of the telemetry emitted by the Tracer. schemaURL string attrs attribute.Set } // InstrumentationVersion returns the version of the library providing instrumentation. func (t *TracerConfig) InstrumentationVersion() string { return t.instrumentationVersion } // InstrumentationAttributes returns the attributes associated with the library // providing instrumentation. func (t *TracerConfig) InstrumentationAttributes() attribute.Set { return t.attrs } // SchemaURL returns the Schema URL of the telemetry emitted by the Tracer. func (t *TracerConfig) SchemaURL() string { return t.schemaURL } // NewTracerConfig applies all the options to a returned TracerConfig. func NewTracerConfig(options ...TracerOption) TracerConfig { var config TracerConfig for _, option := range options { config = option.apply(config) } return config } // TracerOption applies an option to a TracerConfig. type TracerOption interface { apply(TracerConfig) TracerConfig } type tracerOptionFunc func(TracerConfig) TracerConfig func (fn tracerOptionFunc) apply(cfg TracerConfig) TracerConfig { return fn(cfg) } // SpanConfig is a group of options for a Span. type SpanConfig struct { attributes []attribute.KeyValue timestamp time.Time links []Link newRoot bool spanKind SpanKind stackTrace bool } // Attributes describe the associated qualities of a Span. func (cfg *SpanConfig) Attributes() []attribute.KeyValue { return cfg.attributes } // Timestamp is a time in a Span life-cycle. func (cfg *SpanConfig) Timestamp() time.Time { return cfg.timestamp } // StackTrace checks whether stack trace capturing is enabled. func (cfg *SpanConfig) StackTrace() bool { return cfg.stackTrace } // Links are the associations a Span has with other Spans. func (cfg *SpanConfig) Links() []Link { return cfg.links } // NewRoot identifies a Span as the root Span for a new trace. This is // commonly used when an existing trace crosses trust boundaries and the // remote parent span context should be ignored for security. func (cfg *SpanConfig) NewRoot() bool { return cfg.newRoot } // SpanKind is the role a Span has in a trace. func (cfg *SpanConfig) SpanKind() SpanKind { return cfg.spanKind } // NewSpanStartConfig applies all the options to a returned SpanConfig. // No validation is performed on the returned SpanConfig (e.g. no uniqueness // checking or bounding of data), it is left to the SDK to perform this // action. func NewSpanStartConfig(options ...SpanStartOption) SpanConfig { var c SpanConfig for _, option := range options { c = option.applySpanStart(c) } return c } // NewSpanEndConfig applies all the options to a returned SpanConfig. // No validation is performed on the returned SpanConfig (e.g. no uniqueness // checking or bounding of data), it is left to the SDK to perform this // action. func NewSpanEndConfig(options ...SpanEndOption) SpanConfig { var c SpanConfig for _, option := range options { c = option.applySpanEnd(c) } return c } // SpanStartOption applies an option to a SpanConfig. These options are applicable // only when the span is created. type SpanStartOption interface { applySpanStart(SpanConfig) SpanConfig } type spanOptionFunc func(SpanConfig) SpanConfig func (fn spanOptionFunc) applySpanStart(cfg SpanConfig) SpanConfig { return fn(cfg) } // SpanEndOption applies an option to a SpanConfig. These options are // applicable only when the span is ended. type SpanEndOption interface { applySpanEnd(SpanConfig) SpanConfig } // EventConfig is a group of options for an Event. type EventConfig struct { attributes []attribute.KeyValue timestamp time.Time stackTrace bool } // Attributes describe the associated qualities of an Event. func (cfg *EventConfig) Attributes() []attribute.KeyValue { return cfg.attributes } // Timestamp is a time in an Event life-cycle. func (cfg *EventConfig) Timestamp() time.Time { return cfg.timestamp } // StackTrace checks whether stack trace capturing is enabled. func (cfg *EventConfig) StackTrace() bool { return cfg.stackTrace } // NewEventConfig applies all the EventOptions to a returned EventConfig. If no // timestamp option is passed, the returned EventConfig will have a Timestamp // set to the call time, otherwise no validation is performed on the returned // EventConfig. func NewEventConfig(options ...EventOption) EventConfig { var c EventConfig for _, option := range options { c = option.applyEvent(c) } if c.timestamp.IsZero() { c.timestamp = time.Now() } return c } // EventOption applies span event options to an EventConfig. type EventOption interface { applyEvent(EventConfig) EventConfig } // SpanOption are options that can be used at both the beginning and end of a span. type SpanOption interface { SpanStartOption SpanEndOption } // SpanStartEventOption are options that can be used at the start of a span, or with an event. type SpanStartEventOption interface { SpanStartOption EventOption } // SpanEndEventOption are options that can be used at the end of a span, or with an event. type SpanEndEventOption interface { SpanEndOption EventOption } type attributeOption []attribute.KeyValue func (o attributeOption) applySpan(c SpanConfig) SpanConfig { c.attributes = append(c.attributes, []attribute.KeyValue(o)...) return c } func (o attributeOption) applySpanStart(c SpanConfig) SpanConfig { return o.applySpan(c) } func (o attributeOption) applyEvent(c EventConfig) EventConfig { c.attributes = append(c.attributes, []attribute.KeyValue(o)...) return c } var _ SpanStartEventOption = attributeOption{} // WithAttributes adds the attributes related to a span life-cycle event. // These attributes are used to describe the work a Span represents when this // option is provided to a Span's start or end events. Otherwise, these // attributes provide additional information about the event being recorded // (e.g. error, state change, processing progress, system event). // // If multiple of these options are passed the attributes of each successive // option will extend the attributes instead of overwriting. There is no // guarantee of uniqueness in the resulting attributes. func WithAttributes(attributes ...attribute.KeyValue) SpanStartEventOption { return attributeOption(attributes) } // SpanEventOption are options that can be used with an event or a span. type SpanEventOption interface { SpanOption EventOption } type timestampOption time.Time func (o timestampOption) applySpan(c SpanConfig) SpanConfig { c.timestamp = time.Time(o) return c } func (o timestampOption) applySpanStart(c SpanConfig) SpanConfig { return o.applySpan(c) } func (o timestampOption) applySpanEnd(c SpanConfig) SpanConfig { return o.applySpan(c) } func (o timestampOption) applyEvent(c EventConfig) EventConfig { c.timestamp = time.Time(o) return c } var _ SpanEventOption = timestampOption{} // WithTimestamp sets the time of a Span or Event life-cycle moment (e.g. // started, stopped, errored). func WithTimestamp(t time.Time) SpanEventOption { return timestampOption(t) } type stackTraceOption bool func (o stackTraceOption) applyEvent(c EventConfig) EventConfig { c.stackTrace = bool(o) return c } func (o stackTraceOption) applySpan(c SpanConfig) SpanConfig { c.stackTrace = bool(o) return c } func (o stackTraceOption) applySpanEnd(c SpanConfig) SpanConfig { return o.applySpan(c) } // WithStackTrace sets the flag to capture the error with stack trace (e.g. true, false). func WithStackTrace(b bool) SpanEndEventOption { return stackTraceOption(b) } // WithLinks adds links to a Span. The links are added to the existing Span // links, i.e. this does not overwrite. Links with invalid span context are ignored. func WithLinks(links ...Link) SpanStartOption { return spanOptionFunc(func(cfg SpanConfig) SpanConfig { cfg.links = append(cfg.links, links...) return cfg }) } // WithNewRoot specifies that the Span should be treated as a root Span. Any // existing parent span context will be ignored when defining the Span's trace // identifiers. func WithNewRoot() SpanStartOption { return spanOptionFunc(func(cfg SpanConfig) SpanConfig { cfg.newRoot = true return cfg }) } // WithSpanKind sets the SpanKind of a Span. func WithSpanKind(kind SpanKind) SpanStartOption { return spanOptionFunc(func(cfg SpanConfig) SpanConfig { cfg.spanKind = kind return cfg }) } // WithInstrumentationVersion sets the instrumentation version. func WithInstrumentationVersion(version string) TracerOption { return tracerOptionFunc(func(cfg TracerConfig) TracerConfig { cfg.instrumentationVersion = version return cfg }) } // WithInstrumentationAttributes sets the instrumentation attributes. // // The passed attributes will be de-duplicated. func WithInstrumentationAttributes(attr ...attribute.KeyValue) TracerOption { return tracerOptionFunc(func(config TracerConfig) TracerConfig { config.attrs = attribute.NewSet(attr...) return config }) } // WithSchemaURL sets the schema URL for the Tracer. func WithSchemaURL(schemaURL string) TracerOption { return tracerOptionFunc(func(cfg TracerConfig) TracerConfig { cfg.schemaURL = schemaURL return cfg }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/trace/nonrecording.go
vendor/go.opentelemetry.io/otel/trace/nonrecording.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package trace // import "go.opentelemetry.io/otel/trace" // nonRecordingSpan is a minimal implementation of a Span that wraps a // SpanContext. It performs no operations other than to return the wrapped // SpanContext. type nonRecordingSpan struct { noopSpan sc SpanContext } // SpanContext returns the wrapped SpanContext. func (s nonRecordingSpan) SpanContext() SpanContext { return s.sc }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/trace/trace.go
vendor/go.opentelemetry.io/otel/trace/trace.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package trace // import "go.opentelemetry.io/otel/trace" import ( "bytes" "context" "encoding/hex" "encoding/json" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace/embedded" ) const ( // FlagsSampled is a bitmask with the sampled bit set. A SpanContext // with the sampling bit set means the span is sampled. FlagsSampled = TraceFlags(0x01) errInvalidHexID errorConst = "trace-id and span-id can only contain [0-9a-f] characters, all lowercase" errInvalidTraceIDLength errorConst = "hex encoded trace-id must have length equals to 32" errNilTraceID errorConst = "trace-id can't be all zero" errInvalidSpanIDLength errorConst = "hex encoded span-id must have length equals to 16" errNilSpanID errorConst = "span-id can't be all zero" ) type errorConst string func (e errorConst) Error() string { return string(e) } // TraceID is a unique identity of a trace. // nolint:revive // revive complains about stutter of `trace.TraceID`. type TraceID [16]byte var ( nilTraceID TraceID _ json.Marshaler = nilTraceID ) // IsValid checks whether the trace TraceID is valid. A valid trace ID does // not consist of zeros only. func (t TraceID) IsValid() bool { return !bytes.Equal(t[:], nilTraceID[:]) } // MarshalJSON implements a custom marshal function to encode TraceID // as a hex string. func (t TraceID) MarshalJSON() ([]byte, error) { return json.Marshal(t.String()) } // String returns the hex string representation form of a TraceID. func (t TraceID) String() string { return hex.EncodeToString(t[:]) } // SpanID is a unique identity of a span in a trace. type SpanID [8]byte var ( nilSpanID SpanID _ json.Marshaler = nilSpanID ) // IsValid checks whether the SpanID is valid. A valid SpanID does not consist // of zeros only. func (s SpanID) IsValid() bool { return !bytes.Equal(s[:], nilSpanID[:]) } // MarshalJSON implements a custom marshal function to encode SpanID // as a hex string. func (s SpanID) MarshalJSON() ([]byte, error) { return json.Marshal(s.String()) } // String returns the hex string representation form of a SpanID. func (s SpanID) String() string { return hex.EncodeToString(s[:]) } // TraceIDFromHex returns a TraceID from a hex string if it is compliant with // the W3C trace-context specification. See more at // https://www.w3.org/TR/trace-context/#trace-id // nolint:revive // revive complains about stutter of `trace.TraceIDFromHex`. func TraceIDFromHex(h string) (TraceID, error) { t := TraceID{} if len(h) != 32 { return t, errInvalidTraceIDLength } if err := decodeHex(h, t[:]); err != nil { return t, err } if !t.IsValid() { return t, errNilTraceID } return t, nil } // SpanIDFromHex returns a SpanID from a hex string if it is compliant // with the w3c trace-context specification. // See more at https://www.w3.org/TR/trace-context/#parent-id func SpanIDFromHex(h string) (SpanID, error) { s := SpanID{} if len(h) != 16 { return s, errInvalidSpanIDLength } if err := decodeHex(h, s[:]); err != nil { return s, err } if !s.IsValid() { return s, errNilSpanID } return s, nil } func decodeHex(h string, b []byte) error { for _, r := range h { switch { case 'a' <= r && r <= 'f': continue case '0' <= r && r <= '9': continue default: return errInvalidHexID } } decoded, err := hex.DecodeString(h) if err != nil { return err } copy(b, decoded) return nil } // TraceFlags contains flags that can be set on a SpanContext. type TraceFlags byte //nolint:revive // revive complains about stutter of `trace.TraceFlags`. // IsSampled returns if the sampling bit is set in the TraceFlags. func (tf TraceFlags) IsSampled() bool { return tf&FlagsSampled == FlagsSampled } // WithSampled sets the sampling bit in a new copy of the TraceFlags. func (tf TraceFlags) WithSampled(sampled bool) TraceFlags { // nolint:revive // sampled is not a control flag. if sampled { return tf | FlagsSampled } return tf &^ FlagsSampled } // MarshalJSON implements a custom marshal function to encode TraceFlags // as a hex string. func (tf TraceFlags) MarshalJSON() ([]byte, error) { return json.Marshal(tf.String()) } // String returns the hex string representation form of TraceFlags. func (tf TraceFlags) String() string { return hex.EncodeToString([]byte{byte(tf)}[:]) } // SpanContextConfig contains mutable fields usable for constructing // an immutable SpanContext. type SpanContextConfig struct { TraceID TraceID SpanID SpanID TraceFlags TraceFlags TraceState TraceState Remote bool } // NewSpanContext constructs a SpanContext using values from the provided // SpanContextConfig. func NewSpanContext(config SpanContextConfig) SpanContext { return SpanContext{ traceID: config.TraceID, spanID: config.SpanID, traceFlags: config.TraceFlags, traceState: config.TraceState, remote: config.Remote, } } // SpanContext contains identifying trace information about a Span. type SpanContext struct { traceID TraceID spanID SpanID traceFlags TraceFlags traceState TraceState remote bool } var _ json.Marshaler = SpanContext{} // IsValid returns if the SpanContext is valid. A valid span context has a // valid TraceID and SpanID. func (sc SpanContext) IsValid() bool { return sc.HasTraceID() && sc.HasSpanID() } // IsRemote indicates whether the SpanContext represents a remotely-created Span. func (sc SpanContext) IsRemote() bool { return sc.remote } // WithRemote returns a copy of sc with the Remote property set to remote. func (sc SpanContext) WithRemote(remote bool) SpanContext { return SpanContext{ traceID: sc.traceID, spanID: sc.spanID, traceFlags: sc.traceFlags, traceState: sc.traceState, remote: remote, } } // TraceID returns the TraceID from the SpanContext. func (sc SpanContext) TraceID() TraceID { return sc.traceID } // HasTraceID checks if the SpanContext has a valid TraceID. func (sc SpanContext) HasTraceID() bool { return sc.traceID.IsValid() } // WithTraceID returns a new SpanContext with the TraceID replaced. func (sc SpanContext) WithTraceID(traceID TraceID) SpanContext { return SpanContext{ traceID: traceID, spanID: sc.spanID, traceFlags: sc.traceFlags, traceState: sc.traceState, remote: sc.remote, } } // SpanID returns the SpanID from the SpanContext. func (sc SpanContext) SpanID() SpanID { return sc.spanID } // HasSpanID checks if the SpanContext has a valid SpanID. func (sc SpanContext) HasSpanID() bool { return sc.spanID.IsValid() } // WithSpanID returns a new SpanContext with the SpanID replaced. func (sc SpanContext) WithSpanID(spanID SpanID) SpanContext { return SpanContext{ traceID: sc.traceID, spanID: spanID, traceFlags: sc.traceFlags, traceState: sc.traceState, remote: sc.remote, } } // TraceFlags returns the flags from the SpanContext. func (sc SpanContext) TraceFlags() TraceFlags { return sc.traceFlags } // IsSampled returns if the sampling bit is set in the SpanContext's TraceFlags. func (sc SpanContext) IsSampled() bool { return sc.traceFlags.IsSampled() } // WithTraceFlags returns a new SpanContext with the TraceFlags replaced. func (sc SpanContext) WithTraceFlags(flags TraceFlags) SpanContext { return SpanContext{ traceID: sc.traceID, spanID: sc.spanID, traceFlags: flags, traceState: sc.traceState, remote: sc.remote, } } // TraceState returns the TraceState from the SpanContext. func (sc SpanContext) TraceState() TraceState { return sc.traceState } // WithTraceState returns a new SpanContext with the TraceState replaced. func (sc SpanContext) WithTraceState(state TraceState) SpanContext { return SpanContext{ traceID: sc.traceID, spanID: sc.spanID, traceFlags: sc.traceFlags, traceState: state, remote: sc.remote, } } // Equal is a predicate that determines whether two SpanContext values are equal. func (sc SpanContext) Equal(other SpanContext) bool { return sc.traceID == other.traceID && sc.spanID == other.spanID && sc.traceFlags == other.traceFlags && sc.traceState.String() == other.traceState.String() && sc.remote == other.remote } // MarshalJSON implements a custom marshal function to encode a SpanContext. func (sc SpanContext) MarshalJSON() ([]byte, error) { return json.Marshal(SpanContextConfig{ TraceID: sc.traceID, SpanID: sc.spanID, TraceFlags: sc.traceFlags, TraceState: sc.traceState, Remote: sc.remote, }) } // Span is the individual component of a trace. It represents a single named // and timed operation of a workflow that is traced. A Tracer is used to // create a Span and it is then up to the operation the Span represents to // properly end the Span when the operation itself ends. // // Warning: Methods may be added to this interface in minor releases. See // package documentation on API implementation for information on how to set // default behavior for unimplemented methods. type Span interface { // Users of the interface can ignore this. This embedded type is only used // by implementations of this interface. See the "API Implementations" // section of the package documentation for more information. embedded.Span // End completes the Span. The Span is considered complete and ready to be // delivered through the rest of the telemetry pipeline after this method // is called. Therefore, updates to the Span are not allowed after this // method has been called. End(options ...SpanEndOption) // AddEvent adds an event with the provided name and options. AddEvent(name string, options ...EventOption) // AddLink adds a link. // Adding links at span creation using WithLinks is preferred to calling AddLink // later, for contexts that are available during span creation, because head // sampling decisions can only consider information present during span creation. AddLink(link Link) // IsRecording returns the recording state of the Span. It will return // true if the Span is active and events can be recorded. IsRecording() bool // RecordError will record err as an exception span event for this span. An // additional call to SetStatus is required if the Status of the Span should // be set to Error, as this method does not change the Span status. If this // span is not being recorded or err is nil then this method does nothing. RecordError(err error, options ...EventOption) // SpanContext returns the SpanContext of the Span. The returned SpanContext // is usable even after the End method has been called for the Span. SpanContext() SpanContext // SetStatus sets the status of the Span in the form of a code and a // description, provided the status hasn't already been set to a higher // value before (OK > Error > Unset). The description is only included in a // status when the code is for an error. SetStatus(code codes.Code, description string) // SetName sets the Span name. SetName(name string) // SetAttributes sets kv as attributes of the Span. If a key from kv // already exists for an attribute of the Span it will be overwritten with // the value contained in kv. SetAttributes(kv ...attribute.KeyValue) // TracerProvider returns a TracerProvider that can be used to generate // additional Spans on the same telemetry pipeline as the current Span. TracerProvider() TracerProvider } // Link is the relationship between two Spans. The relationship can be within // the same Trace or across different Traces. // // For example, a Link is used in the following situations: // // 1. Batch Processing: A batch of operations may contain operations // associated with one or more traces/spans. Since there can only be one // parent SpanContext, a Link is used to keep reference to the // SpanContext of all operations in the batch. // 2. Public Endpoint: A SpanContext for an in incoming client request on a // public endpoint should be considered untrusted. In such a case, a new // trace with its own identity and sampling decision needs to be created, // but this new trace needs to be related to the original trace in some // form. A Link is used to keep reference to the original SpanContext and // track the relationship. type Link struct { // SpanContext of the linked Span. SpanContext SpanContext // Attributes describe the aspects of the link. Attributes []attribute.KeyValue } // LinkFromContext returns a link encapsulating the SpanContext in the provided ctx. func LinkFromContext(ctx context.Context, attrs ...attribute.KeyValue) Link { return Link{ SpanContext: SpanContextFromContext(ctx), Attributes: attrs, } } // SpanKind is the role a Span plays in a Trace. type SpanKind int // As a convenience, these match the proto definition, see // https://github.com/open-telemetry/opentelemetry-proto/blob/30d237e1ff3ab7aa50e0922b5bebdd93505090af/opentelemetry/proto/trace/v1/trace.proto#L101-L129 // // The unspecified value is not a valid `SpanKind`. Use `ValidateSpanKind()` // to coerce a span kind to a valid value. const ( // SpanKindUnspecified is an unspecified SpanKind and is not a valid // SpanKind. SpanKindUnspecified should be replaced with SpanKindInternal // if it is received. SpanKindUnspecified SpanKind = 0 // SpanKindInternal is a SpanKind for a Span that represents an internal // operation within an application. SpanKindInternal SpanKind = 1 // SpanKindServer is a SpanKind for a Span that represents the operation // of handling a request from a client. SpanKindServer SpanKind = 2 // SpanKindClient is a SpanKind for a Span that represents the operation // of client making a request to a server. SpanKindClient SpanKind = 3 // SpanKindProducer is a SpanKind for a Span that represents the operation // of a producer sending a message to a message broker. Unlike // SpanKindClient and SpanKindServer, there is often no direct // relationship between this kind of Span and a SpanKindConsumer kind. A // SpanKindProducer Span will end once the message is accepted by the // message broker which might not overlap with the processing of that // message. SpanKindProducer SpanKind = 4 // SpanKindConsumer is a SpanKind for a Span that represents the operation // of a consumer receiving a message from a message broker. Like // SpanKindProducer Spans, there is often no direct relationship between // this Span and the Span that produced the message. SpanKindConsumer SpanKind = 5 ) // ValidateSpanKind returns a valid span kind value. This will coerce // invalid values into the default value, SpanKindInternal. func ValidateSpanKind(spanKind SpanKind) SpanKind { switch spanKind { case SpanKindInternal, SpanKindServer, SpanKindClient, SpanKindProducer, SpanKindConsumer: // valid return spanKind default: return SpanKindInternal } } // String returns the specified name of the SpanKind in lower-case. func (sk SpanKind) String() string { switch sk { case SpanKindInternal: return "internal" case SpanKindServer: return "server" case SpanKindClient: return "client" case SpanKindProducer: return "producer" case SpanKindConsumer: return "consumer" default: return "unspecified" } } // Tracer is the creator of Spans. // // Warning: Methods may be added to this interface in minor releases. See // package documentation on API implementation for information on how to set // default behavior for unimplemented methods. type Tracer interface { // Users of the interface can ignore this. This embedded type is only used // by implementations of this interface. See the "API Implementations" // section of the package documentation for more information. embedded.Tracer // Start creates a span and a context.Context containing the newly-created span. // // If the context.Context provided in `ctx` contains a Span then the newly-created // Span will be a child of that span, otherwise it will be a root span. This behavior // can be overridden by providing `WithNewRoot()` as a SpanOption, causing the // newly-created Span to be a root span even if `ctx` contains a Span. // // When creating a Span it is recommended to provide all known span attributes using // the `WithAttributes()` SpanOption as samplers will only have access to the // attributes provided when a Span is created. // // Any Span that is created MUST also be ended. This is the responsibility of the user. // Implementations of this API may leak memory or other resources if Spans are not ended. Start(ctx context.Context, spanName string, opts ...SpanStartOption) (context.Context, Span) } // TracerProvider provides Tracers that are used by instrumentation code to // trace computational workflows. // // A TracerProvider is the collection destination of all Spans from Tracers it // provides, it represents a unique telemetry collection pipeline. How that // pipeline is defined, meaning how those Spans are collected, processed, and // where they are exported, depends on its implementation. Instrumentation // authors do not need to define this implementation, rather just use the // provided Tracers to instrument code. // // Commonly, instrumentation code will accept a TracerProvider implementation // at runtime from its users or it can simply use the globally registered one // (see https://pkg.go.dev/go.opentelemetry.io/otel#GetTracerProvider). // // Warning: Methods may be added to this interface in minor releases. See // package documentation on API implementation for information on how to set // default behavior for unimplemented methods. type TracerProvider interface { // Users of the interface can ignore this. This embedded type is only used // by implementations of this interface. See the "API Implementations" // section of the package documentation for more information. embedded.TracerProvider // Tracer returns a unique Tracer scoped to be used by instrumentation code // to trace computational workflows. The scope and identity of that // instrumentation code is uniquely defined by the name and options passed. // // The passed name needs to uniquely identify instrumentation code. // Therefore, it is recommended that name is the Go package name of the // library providing instrumentation (note: not the code being // instrumented). Instrumentation libraries can have multiple versions, // therefore, the WithInstrumentationVersion option should be used to // distinguish these different codebases. Additionally, instrumentation // libraries may sometimes use traces to communicate different domains of // workflow data (i.e. using spans to communicate workflow events only). If // this is the case, the WithScopeAttributes option should be used to // uniquely identify Tracers that handle the different domains of workflow // data. // // If the same name and options are passed multiple times, the same Tracer // will be returned (it is up to the implementation if this will be the // same underlying instance of that Tracer or not). It is not necessary to // call this multiple times with the same name and options to get an // up-to-date Tracer. All implementations will ensure any TracerProvider // configuration changes are propagated to all provided Tracers. // // If name is empty, then an implementation defined default name will be // used instead. // // This method is safe to call concurrently. Tracer(name string, options ...TracerOption) Tracer }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/trace/noop.go
vendor/go.opentelemetry.io/otel/trace/noop.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package trace // import "go.opentelemetry.io/otel/trace" import ( "context" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace/embedded" ) // NewNoopTracerProvider returns an implementation of TracerProvider that // performs no operations. The Tracer and Spans created from the returned // TracerProvider also perform no operations. // // Deprecated: Use [go.opentelemetry.io/otel/trace/noop.NewTracerProvider] // instead. func NewNoopTracerProvider() TracerProvider { return noopTracerProvider{} } type noopTracerProvider struct{ embedded.TracerProvider } var _ TracerProvider = noopTracerProvider{} // Tracer returns noop implementation of Tracer. func (p noopTracerProvider) Tracer(string, ...TracerOption) Tracer { return noopTracer{} } // noopTracer is an implementation of Tracer that performs no operations. type noopTracer struct{ embedded.Tracer } var _ Tracer = noopTracer{} // Start carries forward a non-recording Span, if one is present in the context, otherwise it // creates a no-op Span. func (t noopTracer) Start(ctx context.Context, name string, _ ...SpanStartOption) (context.Context, Span) { span := SpanFromContext(ctx) if _, ok := span.(nonRecordingSpan); !ok { // span is likely already a noopSpan, but let's be sure span = noopSpanInstance } return ContextWithSpan(ctx, span), span } // noopSpan is an implementation of Span that performs no operations. type noopSpan struct{ embedded.Span } var noopSpanInstance Span = noopSpan{} // SpanContext returns an empty span context. func (noopSpan) SpanContext() SpanContext { return SpanContext{} } // IsRecording always returns false. func (noopSpan) IsRecording() bool { return false } // SetStatus does nothing. func (noopSpan) SetStatus(codes.Code, string) {} // SetError does nothing. func (noopSpan) SetError(bool) {} // SetAttributes does nothing. func (noopSpan) SetAttributes(...attribute.KeyValue) {} // End does nothing. func (noopSpan) End(...SpanEndOption) {} // RecordError does nothing. func (noopSpan) RecordError(error, ...EventOption) {} // AddEvent does nothing. func (noopSpan) AddEvent(string, ...EventOption) {} // AddLink does nothing. func (noopSpan) AddLink(Link) {} // SetName does nothing. func (noopSpan) SetName(string) {} // TracerProvider returns a no-op TracerProvider. func (noopSpan) TracerProvider() TracerProvider { return noopTracerProvider{} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/trace/tracestate.go
vendor/go.opentelemetry.io/otel/trace/tracestate.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package trace // import "go.opentelemetry.io/otel/trace" import ( "encoding/json" "fmt" "strings" ) const ( maxListMembers = 32 listDelimiters = "," memberDelimiter = "=" errInvalidKey errorConst = "invalid tracestate key" errInvalidValue errorConst = "invalid tracestate value" errInvalidMember errorConst = "invalid tracestate list-member" errMemberNumber errorConst = "too many list-members in tracestate" errDuplicate errorConst = "duplicate list-member in tracestate" ) type member struct { Key string Value string } // according to (chr = %x20 / (nblk-char = %x21-2B / %x2D-3C / %x3E-7E) ) // means (chr = %x20-2B / %x2D-3C / %x3E-7E) . func checkValueChar(v byte) bool { return v >= '\x20' && v <= '\x7e' && v != '\x2c' && v != '\x3d' } // according to (nblk-chr = %x21-2B / %x2D-3C / %x3E-7E) . func checkValueLast(v byte) bool { return v >= '\x21' && v <= '\x7e' && v != '\x2c' && v != '\x3d' } // based on the W3C Trace Context specification // // value = (0*255(chr)) nblk-chr // nblk-chr = %x21-2B / %x2D-3C / %x3E-7E // chr = %x20 / nblk-chr // // see https://www.w3.org/TR/trace-context-1/#value func checkValue(val string) bool { n := len(val) if n == 0 || n > 256 { return false } for i := 0; i < n-1; i++ { if !checkValueChar(val[i]) { return false } } return checkValueLast(val[n-1]) } func checkKeyRemain(key string) bool { // ( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ) for _, v := range key { if isAlphaNum(byte(v)) { continue } switch v { case '_', '-', '*', '/': continue } return false } return true } // according to // // simple-key = lcalpha (0*255( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )) // system-id = lcalpha (0*13( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )) // // param n is remain part length, should be 255 in simple-key or 13 in system-id. func checkKeyPart(key string, n int) bool { if len(key) == 0 { return false } first := key[0] // key's first char ret := len(key[1:]) <= n ret = ret && first >= 'a' && first <= 'z' return ret && checkKeyRemain(key[1:]) } func isAlphaNum(c byte) bool { if c >= 'a' && c <= 'z' { return true } return c >= '0' && c <= '9' } // according to // // tenant-id = ( lcalpha / DIGIT ) 0*240( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ) // // param n is remain part length, should be 240 exactly. func checkKeyTenant(key string, n int) bool { if len(key) == 0 { return false } return isAlphaNum(key[0]) && len(key[1:]) <= n && checkKeyRemain(key[1:]) } // based on the W3C Trace Context specification // // key = simple-key / multi-tenant-key // simple-key = lcalpha (0*255( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )) // multi-tenant-key = tenant-id "@" system-id // tenant-id = ( lcalpha / DIGIT ) (0*240( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )) // system-id = lcalpha (0*13( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )) // lcalpha = %x61-7A ; a-z // // see https://www.w3.org/TR/trace-context-1/#tracestate-header. func checkKey(key string) bool { tenant, system, ok := strings.Cut(key, "@") if !ok { return checkKeyPart(key, 255) } return checkKeyTenant(tenant, 240) && checkKeyPart(system, 13) } func newMember(key, value string) (member, error) { if !checkKey(key) { return member{}, errInvalidKey } if !checkValue(value) { return member{}, errInvalidValue } return member{Key: key, Value: value}, nil } func parseMember(m string) (member, error) { key, val, ok := strings.Cut(m, memberDelimiter) if !ok { return member{}, fmt.Errorf("%w: %s", errInvalidMember, m) } key = strings.TrimLeft(key, " \t") val = strings.TrimRight(val, " \t") result, e := newMember(key, val) if e != nil { return member{}, fmt.Errorf("%w: %s", errInvalidMember, m) } return result, nil } // String encodes member into a string compliant with the W3C Trace Context // specification. func (m member) String() string { return m.Key + "=" + m.Value } // TraceState provides additional vendor-specific trace identification // information across different distributed tracing systems. It represents an // immutable list consisting of key/value pairs, each pair is referred to as a // list-member. // // TraceState conforms to the W3C Trace Context specification // (https://www.w3.org/TR/trace-context-1). All operations that create or copy // a TraceState do so by validating all input and will only produce TraceState // that conform to the specification. Specifically, this means that all // list-member's key/value pairs are valid, no duplicate list-members exist, // and the maximum number of list-members (32) is not exceeded. type TraceState struct { //nolint:revive // revive complains about stutter of `trace.TraceState` // list is the members in order. list []member } var _ json.Marshaler = TraceState{} // ParseTraceState attempts to decode a TraceState from the passed // string. It returns an error if the input is invalid according to the W3C // Trace Context specification. func ParseTraceState(ts string) (TraceState, error) { if ts == "" { return TraceState{}, nil } wrapErr := func(err error) error { return fmt.Errorf("failed to parse tracestate: %w", err) } var members []member found := make(map[string]struct{}) for ts != "" { var memberStr string memberStr, ts, _ = strings.Cut(ts, listDelimiters) if len(memberStr) == 0 { continue } m, err := parseMember(memberStr) if err != nil { return TraceState{}, wrapErr(err) } if _, ok := found[m.Key]; ok { return TraceState{}, wrapErr(errDuplicate) } found[m.Key] = struct{}{} members = append(members, m) if n := len(members); n > maxListMembers { return TraceState{}, wrapErr(errMemberNumber) } } return TraceState{list: members}, nil } // MarshalJSON marshals the TraceState into JSON. func (ts TraceState) MarshalJSON() ([]byte, error) { return json.Marshal(ts.String()) } // String encodes the TraceState into a string compliant with the W3C // Trace Context specification. The returned string will be invalid if the // TraceState contains any invalid members. func (ts TraceState) String() string { if len(ts.list) == 0 { return "" } var n int n += len(ts.list) // member delimiters: '=' n += len(ts.list) - 1 // list delimiters: ',' for _, mem := range ts.list { n += len(mem.Key) n += len(mem.Value) } var sb strings.Builder sb.Grow(n) _, _ = sb.WriteString(ts.list[0].Key) _ = sb.WriteByte('=') _, _ = sb.WriteString(ts.list[0].Value) for i := 1; i < len(ts.list); i++ { _ = sb.WriteByte(listDelimiters[0]) _, _ = sb.WriteString(ts.list[i].Key) _ = sb.WriteByte('=') _, _ = sb.WriteString(ts.list[i].Value) } return sb.String() } // Get returns the value paired with key from the corresponding TraceState // list-member if it exists, otherwise an empty string is returned. func (ts TraceState) Get(key string) string { for _, member := range ts.list { if member.Key == key { return member.Value } } return "" } // Insert adds a new list-member defined by the key/value pair to the // TraceState. If a list-member already exists for the given key, that // list-member's value is updated. The new or updated list-member is always // moved to the beginning of the TraceState as specified by the W3C Trace // Context specification. // // If key or value are invalid according to the W3C Trace Context // specification an error is returned with the original TraceState. // // If adding a new list-member means the TraceState would have more members // then is allowed, the new list-member will be inserted and the right-most // list-member will be dropped in the returned TraceState. func (ts TraceState) Insert(key, value string) (TraceState, error) { m, err := newMember(key, value) if err != nil { return ts, err } n := len(ts.list) found := n for i := range ts.list { if ts.list[i].Key == key { found = i } } cTS := TraceState{} if found == n && n < maxListMembers { cTS.list = make([]member, n+1) } else { cTS.list = make([]member, n) } cTS.list[0] = m // When the number of members exceeds capacity, drop the "right-most". copy(cTS.list[1:], ts.list[0:found]) if found < n { copy(cTS.list[1+found:], ts.list[found+1:]) } return cTS, nil } // Delete returns a copy of the TraceState with the list-member identified by // key removed. func (ts TraceState) Delete(key string) TraceState { members := make([]member, ts.Len()) copy(members, ts.list) for i, member := range ts.list { if member.Key == key { members = append(members[:i], members[i+1:]...) // TraceState should contain no duplicate members. break } } return TraceState{list: members} } // Len returns the number of list-members in the TraceState. func (ts TraceState) Len() int { return len(ts.list) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/trace/context.go
vendor/go.opentelemetry.io/otel/trace/context.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package trace // import "go.opentelemetry.io/otel/trace" import "context" type traceContextKeyType int const currentSpanKey traceContextKeyType = iota // ContextWithSpan returns a copy of parent with span set as the current Span. func ContextWithSpan(parent context.Context, span Span) context.Context { return context.WithValue(parent, currentSpanKey, span) } // ContextWithSpanContext returns a copy of parent with sc as the current // Span. The Span implementation that wraps sc is non-recording and performs // no operations other than to return sc as the SpanContext from the // SpanContext method. func ContextWithSpanContext(parent context.Context, sc SpanContext) context.Context { return ContextWithSpan(parent, nonRecordingSpan{sc: sc}) } // ContextWithRemoteSpanContext returns a copy of parent with rsc set explicly // as a remote SpanContext and as the current Span. The Span implementation // that wraps rsc is non-recording and performs no operations other than to // return rsc as the SpanContext from the SpanContext method. func ContextWithRemoteSpanContext(parent context.Context, rsc SpanContext) context.Context { return ContextWithSpanContext(parent, rsc.WithRemote(true)) } // SpanFromContext returns the current Span from ctx. // // If no Span is currently set in ctx an implementation of a Span that // performs no operations is returned. func SpanFromContext(ctx context.Context) Span { if ctx == nil { return noopSpanInstance } if span, ok := ctx.Value(currentSpanKey).(Span); ok { return span } return noopSpanInstance } // SpanContextFromContext returns the current Span's SpanContext. func SpanContextFromContext(ctx context.Context) SpanContext { return SpanFromContext(ctx).SpanContext() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/trace/doc.go
vendor/go.opentelemetry.io/otel/trace/doc.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 /* Package trace provides an implementation of the tracing part of the OpenTelemetry API. To participate in distributed traces a Span needs to be created for the operation being performed as part of a traced workflow. In its simplest form: var tracer trace.Tracer func init() { tracer = otel.Tracer("instrumentation/package/name") } func operation(ctx context.Context) { var span trace.Span ctx, span = tracer.Start(ctx, "operation") defer span.End() // ... } A Tracer is unique to the instrumentation and is used to create Spans. Instrumentation should be designed to accept a TracerProvider from which it can create its own unique Tracer. Alternatively, the registered global TracerProvider from the go.opentelemetry.io/otel package can be used as a default. const ( name = "instrumentation/package/name" version = "0.1.0" ) type Instrumentation struct { tracer trace.Tracer } func NewInstrumentation(tp trace.TracerProvider) *Instrumentation { if tp == nil { tp = otel.TracerProvider() } return &Instrumentation{ tracer: tp.Tracer(name, trace.WithInstrumentationVersion(version)), } } func operation(ctx context.Context, inst *Instrumentation) { var span trace.Span ctx, span = inst.tracer.Start(ctx, "operation") defer span.End() // ... } # API Implementations This package does not conform to the standard Go versioning policy; all of its interfaces may have methods added to them without a package major version bump. This non-standard API evolution could surprise an uninformed implementation author. They could unknowingly build their implementation in a way that would result in a runtime panic for their users that update to the new API. The API is designed to help inform an instrumentation author about this non-standard API evolution. It requires them to choose a default behavior for unimplemented interface methods. There are three behavior choices they can make: - Compilation failure - Panic - Default to another implementation All interfaces in this API embed a corresponding interface from [go.opentelemetry.io/otel/trace/embedded]. If an author wants the default behavior of their implementations to be a compilation failure, signaling to their users they need to update to the latest version of that implementation, they need to embed the corresponding interface from [go.opentelemetry.io/otel/trace/embedded] in their implementation. For example, import "go.opentelemetry.io/otel/trace/embedded" type TracerProvider struct { embedded.TracerProvider // ... } If an author wants the default behavior of their implementations to panic, they can embed the API interface directly. import "go.opentelemetry.io/otel/trace" type TracerProvider struct { trace.TracerProvider // ... } This option is not recommended. It will lead to publishing packages that contain runtime panics when users update to newer versions of [go.opentelemetry.io/otel/trace], which may be done with a trasitive dependency. Finally, an author can embed another implementation in theirs. The embedded implementation will be used for methods not defined by the author. For example, an author who wants to default to silently dropping the call can use [go.opentelemetry.io/otel/trace/noop]: import "go.opentelemetry.io/otel/trace/noop" type TracerProvider struct { noop.TracerProvider // ... } It is strongly recommended that authors only embed [go.opentelemetry.io/otel/trace/noop] if they choose this default behavior. That implementation is the only one OpenTelemetry authors can guarantee will fully implement all the API interfaces when a user updates their API. */ package trace // import "go.opentelemetry.io/otel/trace"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/trace/embedded/embedded.go
vendor/go.opentelemetry.io/otel/trace/embedded/embedded.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Package embedded provides interfaces embedded within the [OpenTelemetry // trace API]. // // Implementers of the [OpenTelemetry trace API] can embed the relevant type // from this package into their implementation directly. Doing so will result // in a compilation error for users when the [OpenTelemetry trace API] is // extended (which is something that can happen without a major version bump of // the API package). // // [OpenTelemetry trace API]: https://pkg.go.dev/go.opentelemetry.io/otel/trace package embedded // import "go.opentelemetry.io/otel/trace/embedded" // TracerProvider is embedded in // [go.opentelemetry.io/otel/trace.TracerProvider]. // // Embed this interface in your implementation of the // [go.opentelemetry.io/otel/trace.TracerProvider] if you want users to // experience a compilation error, signaling they need to update to your latest // implementation, when the [go.opentelemetry.io/otel/trace.TracerProvider] // interface is extended (which is something that can happen without a major // version bump of the API package). type TracerProvider interface{ tracerProvider() } // Tracer is embedded in [go.opentelemetry.io/otel/trace.Tracer]. // // Embed this interface in your implementation of the // [go.opentelemetry.io/otel/trace.Tracer] if you want users to experience a // compilation error, signaling they need to update to your latest // implementation, when the [go.opentelemetry.io/otel/trace.Tracer] interface // is extended (which is something that can happen without a major version bump // of the API package). type Tracer interface{ tracer() } // Span is embedded in [go.opentelemetry.io/otel/trace.Span]. // // Embed this interface in your implementation of the // [go.opentelemetry.io/otel/trace.Span] if you want users to experience a // compilation error, signaling they need to update to your latest // implementation, when the [go.opentelemetry.io/otel/trace.Span] interface is // extended (which is something that can happen without a major version bump of // the API package). type Span interface{ span() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/internal/rawhelpers.go
vendor/go.opentelemetry.io/otel/internal/rawhelpers.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package internal // import "go.opentelemetry.io/otel/internal" import ( "math" "unsafe" ) func BoolToRaw(b bool) uint64 { // nolint:revive // b is not a control flag. if b { return 1 } return 0 } func RawToBool(r uint64) bool { return r != 0 } func Int64ToRaw(i int64) uint64 { return uint64(i) } func RawToInt64(r uint64) int64 { return int64(r) } func Float64ToRaw(f float64) uint64 { return math.Float64bits(f) } func RawToFloat64(r uint64) float64 { return math.Float64frombits(r) } func RawPtrToFloat64Ptr(r *uint64) *float64 { return (*float64)(unsafe.Pointer(r)) } func RawPtrToInt64Ptr(r *uint64) *int64 { return (*int64)(unsafe.Pointer(r)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/internal/gen.go
vendor/go.opentelemetry.io/otel/internal/gen.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package internal // import "go.opentelemetry.io/otel/internal" //go:generate gotmpl --body=./shared/matchers/expectation.go.tmpl "--data={}" --out=matchers/expectation.go //go:generate gotmpl --body=./shared/matchers/expecter.go.tmpl "--data={}" --out=matchers/expecter.go //go:generate gotmpl --body=./shared/matchers/temporal_matcher.go.tmpl "--data={}" --out=matchers/temporal_matcher.go //go:generate gotmpl --body=./shared/internaltest/alignment.go.tmpl "--data={}" --out=internaltest/alignment.go //go:generate gotmpl --body=./shared/internaltest/env.go.tmpl "--data={}" --out=internaltest/env.go //go:generate gotmpl --body=./shared/internaltest/env_test.go.tmpl "--data={}" --out=internaltest/env_test.go //go:generate gotmpl --body=./shared/internaltest/errors.go.tmpl "--data={}" --out=internaltest/errors.go //go:generate gotmpl --body=./shared/internaltest/harness.go.tmpl "--data={\"matchersImportPath\": \"go.opentelemetry.io/otel/internal/matchers\"}" --out=internaltest/harness.go //go:generate gotmpl --body=./shared/internaltest/text_map_carrier.go.tmpl "--data={}" --out=internaltest/text_map_carrier.go //go:generate gotmpl --body=./shared/internaltest/text_map_carrier_test.go.tmpl "--data={}" --out=internaltest/text_map_carrier_test.go //go:generate gotmpl --body=./shared/internaltest/text_map_propagator.go.tmpl "--data={}" --out=internaltest/text_map_propagator.go //go:generate gotmpl --body=./shared/internaltest/text_map_propagator_test.go.tmpl "--data={}" --out=internaltest/text_map_propagator_test.go
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/internal/attribute/attribute.go
vendor/go.opentelemetry.io/otel/internal/attribute/attribute.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 /* Package attribute provide several helper functions for some commonly used logic of processing attributes. */ package attribute // import "go.opentelemetry.io/otel/internal/attribute" import ( "reflect" ) // BoolSliceValue converts a bool slice into an array with same elements as slice. func BoolSliceValue(v []bool) interface{} { var zero bool cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem() reflect.Copy(cp, reflect.ValueOf(v)) return cp.Interface() } // Int64SliceValue converts an int64 slice into an array with same elements as slice. func Int64SliceValue(v []int64) interface{} { var zero int64 cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem() reflect.Copy(cp, reflect.ValueOf(v)) return cp.Interface() } // Float64SliceValue converts a float64 slice into an array with same elements as slice. func Float64SliceValue(v []float64) interface{} { var zero float64 cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem() reflect.Copy(cp, reflect.ValueOf(v)) return cp.Interface() } // StringSliceValue converts a string slice into an array with same elements as slice. func StringSliceValue(v []string) interface{} { var zero string cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem() reflect.Copy(cp, reflect.ValueOf(v)) return cp.Interface() } // AsBoolSlice converts a bool array into a slice into with same elements as array. func AsBoolSlice(v interface{}) []bool { rv := reflect.ValueOf(v) if rv.Type().Kind() != reflect.Array { return nil } var zero bool correctLen := rv.Len() correctType := reflect.ArrayOf(correctLen, reflect.TypeOf(zero)) cpy := reflect.New(correctType) _ = reflect.Copy(cpy.Elem(), rv) return cpy.Elem().Slice(0, correctLen).Interface().([]bool) } // AsInt64Slice converts an int64 array into a slice into with same elements as array. func AsInt64Slice(v interface{}) []int64 { rv := reflect.ValueOf(v) if rv.Type().Kind() != reflect.Array { return nil } var zero int64 correctLen := rv.Len() correctType := reflect.ArrayOf(correctLen, reflect.TypeOf(zero)) cpy := reflect.New(correctType) _ = reflect.Copy(cpy.Elem(), rv) return cpy.Elem().Slice(0, correctLen).Interface().([]int64) } // AsFloat64Slice converts a float64 array into a slice into with same elements as array. func AsFloat64Slice(v interface{}) []float64 { rv := reflect.ValueOf(v) if rv.Type().Kind() != reflect.Array { return nil } var zero float64 correctLen := rv.Len() correctType := reflect.ArrayOf(correctLen, reflect.TypeOf(zero)) cpy := reflect.New(correctType) _ = reflect.Copy(cpy.Elem(), rv) return cpy.Elem().Slice(0, correctLen).Interface().([]float64) } // AsStringSlice converts a string array into a slice into with same elements as array. func AsStringSlice(v interface{}) []string { rv := reflect.ValueOf(v) if rv.Type().Kind() != reflect.Array { return nil } var zero string correctLen := rv.Len() correctType := reflect.ArrayOf(correctLen, reflect.TypeOf(zero)) cpy := reflect.New(correctType) _ = reflect.Copy(cpy.Elem(), rv) return cpy.Elem().Slice(0, correctLen).Interface().([]string) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/attribute/kv.go
vendor/go.opentelemetry.io/otel/attribute/kv.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" import ( "fmt" ) // KeyValue holds a key and value pair. type KeyValue struct { Key Key Value Value } // Valid returns if kv is a valid OpenTelemetry attribute. func (kv KeyValue) Valid() bool { return kv.Key.Defined() && kv.Value.Type() != INVALID } // Bool creates a KeyValue with a BOOL Value type. func Bool(k string, v bool) KeyValue { return Key(k).Bool(v) } // BoolSlice creates a KeyValue with a BOOLSLICE Value type. func BoolSlice(k string, v []bool) KeyValue { return Key(k).BoolSlice(v) } // Int creates a KeyValue with an INT64 Value type. func Int(k string, v int) KeyValue { return Key(k).Int(v) } // IntSlice creates a KeyValue with an INT64SLICE Value type. func IntSlice(k string, v []int) KeyValue { return Key(k).IntSlice(v) } // Int64 creates a KeyValue with an INT64 Value type. func Int64(k string, v int64) KeyValue { return Key(k).Int64(v) } // Int64Slice creates a KeyValue with an INT64SLICE Value type. func Int64Slice(k string, v []int64) KeyValue { return Key(k).Int64Slice(v) } // Float64 creates a KeyValue with a FLOAT64 Value type. func Float64(k string, v float64) KeyValue { return Key(k).Float64(v) } // Float64Slice creates a KeyValue with a FLOAT64SLICE Value type. func Float64Slice(k string, v []float64) KeyValue { return Key(k).Float64Slice(v) } // String creates a KeyValue with a STRING Value type. func String(k, v string) KeyValue { return Key(k).String(v) } // StringSlice creates a KeyValue with a STRINGSLICE Value type. func StringSlice(k string, v []string) KeyValue { return Key(k).StringSlice(v) } // Stringer creates a new key-value pair with a passed name and a string // value generated by the passed Stringer interface. func Stringer(k string, v fmt.Stringer) KeyValue { return Key(k).String(v.String()) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/attribute/type_string.go
vendor/go.opentelemetry.io/otel/attribute/type_string.go
// Code generated by "stringer -type=Type"; DO NOT EDIT. package attribute import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[INVALID-0] _ = x[BOOL-1] _ = x[INT64-2] _ = x[FLOAT64-3] _ = x[STRING-4] _ = x[BOOLSLICE-5] _ = x[INT64SLICE-6] _ = x[FLOAT64SLICE-7] _ = x[STRINGSLICE-8] } const _Type_name = "INVALIDBOOLINT64FLOAT64STRINGBOOLSLICEINT64SLICEFLOAT64SLICESTRINGSLICE" var _Type_index = [...]uint8{0, 7, 11, 16, 23, 29, 38, 48, 60, 71} func (i Type) String() string { if i < 0 || i >= Type(len(_Type_index)-1) { return "Type(" + strconv.FormatInt(int64(i), 10) + ")" } return _Type_name[_Type_index[i]:_Type_index[i+1]] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/attribute/filter.go
vendor/go.opentelemetry.io/otel/attribute/filter.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" // Filter supports removing certain attributes from attribute sets. When // the filter returns true, the attribute will be kept in the filtered // attribute set. When the filter returns false, the attribute is excluded // from the filtered attribute set, and the attribute instead appears in // the removed list of excluded attributes. type Filter func(KeyValue) bool // NewAllowKeysFilter returns a Filter that only allows attributes with one of // the provided keys. // // If keys is empty a deny-all filter is returned. func NewAllowKeysFilter(keys ...Key) Filter { if len(keys) <= 0 { return func(kv KeyValue) bool { return false } } allowed := make(map[Key]struct{}) for _, k := range keys { allowed[k] = struct{}{} } return func(kv KeyValue) bool { _, ok := allowed[kv.Key] return ok } } // NewDenyKeysFilter returns a Filter that only allows attributes // that do not have one of the provided keys. // // If keys is empty an allow-all filter is returned. func NewDenyKeysFilter(keys ...Key) Filter { if len(keys) <= 0 { return func(kv KeyValue) bool { return true } } forbid := make(map[Key]struct{}) for _, k := range keys { forbid[k] = struct{}{} } return func(kv KeyValue) bool { _, ok := forbid[kv.Key] return !ok } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/attribute/iterator.go
vendor/go.opentelemetry.io/otel/attribute/iterator.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" // Iterator allows iterating over the set of attributes in order, sorted by // key. type Iterator struct { storage *Set idx int } // MergeIterator supports iterating over two sets of attributes while // eliminating duplicate values from the combined set. The first iterator // value takes precedence. type MergeIterator struct { one oneIterator two oneIterator current KeyValue } type oneIterator struct { iter Iterator done bool attr KeyValue } // Next moves the iterator to the next position. Returns false if there are no // more attributes. func (i *Iterator) Next() bool { i.idx++ return i.idx < i.Len() } // Label returns current KeyValue. Must be called only after Next returns // true. // // Deprecated: Use Attribute instead. func (i *Iterator) Label() KeyValue { return i.Attribute() } // Attribute returns the current KeyValue of the Iterator. It must be called // only after Next returns true. func (i *Iterator) Attribute() KeyValue { kv, _ := i.storage.Get(i.idx) return kv } // IndexedLabel returns current index and attribute. Must be called only // after Next returns true. // // Deprecated: Use IndexedAttribute instead. func (i *Iterator) IndexedLabel() (int, KeyValue) { return i.idx, i.Attribute() } // IndexedAttribute returns current index and attribute. Must be called only // after Next returns true. func (i *Iterator) IndexedAttribute() (int, KeyValue) { return i.idx, i.Attribute() } // Len returns a number of attributes in the iterated set. func (i *Iterator) Len() int { return i.storage.Len() } // ToSlice is a convenience function that creates a slice of attributes from // the passed iterator. The iterator is set up to start from the beginning // before creating the slice. func (i *Iterator) ToSlice() []KeyValue { l := i.Len() if l == 0 { return nil } i.idx = -1 slice := make([]KeyValue, 0, l) for i.Next() { slice = append(slice, i.Attribute()) } return slice } // NewMergeIterator returns a MergeIterator for merging two attribute sets. // Duplicates are resolved by taking the value from the first set. func NewMergeIterator(s1, s2 *Set) MergeIterator { mi := MergeIterator{ one: makeOne(s1.Iter()), two: makeOne(s2.Iter()), } return mi } func makeOne(iter Iterator) oneIterator { oi := oneIterator{ iter: iter, } oi.advance() return oi } func (oi *oneIterator) advance() { if oi.done = !oi.iter.Next(); !oi.done { oi.attr = oi.iter.Attribute() } } // Next returns true if there is another attribute available. func (m *MergeIterator) Next() bool { if m.one.done && m.two.done { return false } if m.one.done { m.current = m.two.attr m.two.advance() return true } if m.two.done { m.current = m.one.attr m.one.advance() return true } if m.one.attr.Key == m.two.attr.Key { m.current = m.one.attr // first iterator attribute value wins m.one.advance() m.two.advance() return true } if m.one.attr.Key < m.two.attr.Key { m.current = m.one.attr m.one.advance() return true } m.current = m.two.attr m.two.advance() return true } // Label returns the current value after Next() returns true. // // Deprecated: Use Attribute instead. func (m *MergeIterator) Label() KeyValue { return m.current } // Attribute returns the current value after Next() returns true. func (m *MergeIterator) Attribute() KeyValue { return m.current }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/attribute/set.go
vendor/go.opentelemetry.io/otel/attribute/set.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" import ( "cmp" "encoding/json" "reflect" "slices" "sort" ) type ( // Set is the representation for a distinct attribute set. It manages an // immutable set of attributes, with an internal cache for storing // attribute encodings. // // This type will remain comparable for backwards compatibility. The // equivalence of Sets across versions is not guaranteed to be stable. // Prior versions may find two Sets to be equal or not when compared // directly (i.e. ==), but subsequent versions may not. Users should use // the Equals method to ensure stable equivalence checking. // // Users should also use the Distinct returned from Equivalent as a map key // instead of a Set directly. In addition to that type providing guarantees // on stable equivalence, it may also provide performance improvements. Set struct { equivalent Distinct } // Distinct is a unique identifier of a Set. // // Distinct is designed to be ensures equivalence stability: comparisons // will return the save value across versions. For this reason, Distinct // should always be used as a map key instead of a Set. Distinct struct { iface interface{} } // Sortable implements sort.Interface, used for sorting KeyValue. // // Deprecated: This type is no longer used. It was added as a performance // optimization for Go < 1.21 that is no longer needed (Go < 1.21 is no // longer supported by the module). Sortable []KeyValue ) var ( // keyValueType is used in computeDistinctReflect. keyValueType = reflect.TypeOf(KeyValue{}) // emptySet is returned for empty attribute sets. emptySet = &Set{ equivalent: Distinct{ iface: [0]KeyValue{}, }, } ) // EmptySet returns a reference to a Set with no elements. // // This is a convenience provided for optimized calling utility. func EmptySet() *Set { return emptySet } // reflectValue abbreviates reflect.ValueOf(d). func (d Distinct) reflectValue() reflect.Value { return reflect.ValueOf(d.iface) } // Valid returns true if this value refers to a valid Set. func (d Distinct) Valid() bool { return d.iface != nil } // Len returns the number of attributes in this set. func (l *Set) Len() int { if l == nil || !l.equivalent.Valid() { return 0 } return l.equivalent.reflectValue().Len() } // Get returns the KeyValue at ordered position idx in this set. func (l *Set) Get(idx int) (KeyValue, bool) { if l == nil || !l.equivalent.Valid() { return KeyValue{}, false } value := l.equivalent.reflectValue() if idx >= 0 && idx < value.Len() { // Note: The Go compiler successfully avoids an allocation for // the interface{} conversion here: return value.Index(idx).Interface().(KeyValue), true } return KeyValue{}, false } // Value returns the value of a specified key in this set. func (l *Set) Value(k Key) (Value, bool) { if l == nil || !l.equivalent.Valid() { return Value{}, false } rValue := l.equivalent.reflectValue() vlen := rValue.Len() idx := sort.Search(vlen, func(idx int) bool { return rValue.Index(idx).Interface().(KeyValue).Key >= k }) if idx >= vlen { return Value{}, false } keyValue := rValue.Index(idx).Interface().(KeyValue) if k == keyValue.Key { return keyValue.Value, true } return Value{}, false } // HasValue tests whether a key is defined in this set. func (l *Set) HasValue(k Key) bool { if l == nil { return false } _, ok := l.Value(k) return ok } // Iter returns an iterator for visiting the attributes in this set. func (l *Set) Iter() Iterator { return Iterator{ storage: l, idx: -1, } } // ToSlice returns the set of attributes belonging to this set, sorted, where // keys appear no more than once. func (l *Set) ToSlice() []KeyValue { iter := l.Iter() return iter.ToSlice() } // Equivalent returns a value that may be used as a map key. The Distinct type // guarantees that the result will equal the equivalent. Distinct value of any // attribute set with the same elements as this, where sets are made unique by // choosing the last value in the input for any given key. func (l *Set) Equivalent() Distinct { if l == nil || !l.equivalent.Valid() { return emptySet.equivalent } return l.equivalent } // Equals returns true if the argument set is equivalent to this set. func (l *Set) Equals(o *Set) bool { return l.Equivalent() == o.Equivalent() } // Encoded returns the encoded form of this set, according to encoder. func (l *Set) Encoded(encoder Encoder) string { if l == nil || encoder == nil { return "" } return encoder.Encode(l.Iter()) } func empty() Set { return Set{ equivalent: emptySet.equivalent, } } // NewSet returns a new Set. See the documentation for // NewSetWithSortableFiltered for more details. // // Except for empty sets, this method adds an additional allocation compared // with calls that include a Sortable. func NewSet(kvs ...KeyValue) Set { s, _ := NewSetWithFiltered(kvs, nil) return s } // NewSetWithSortable returns a new Set. See the documentation for // NewSetWithSortableFiltered for more details. // // This call includes a Sortable option as a memory optimization. // // Deprecated: Use [NewSet] instead. func NewSetWithSortable(kvs []KeyValue, _ *Sortable) Set { s, _ := NewSetWithFiltered(kvs, nil) return s } // NewSetWithFiltered returns a new Set. See the documentation for // NewSetWithSortableFiltered for more details. // // This call includes a Filter to include/exclude attribute keys from the // return value. Excluded keys are returned as a slice of attribute values. func NewSetWithFiltered(kvs []KeyValue, filter Filter) (Set, []KeyValue) { // Check for empty set. if len(kvs) == 0 { return empty(), nil } // Stable sort so the following de-duplication can implement // last-value-wins semantics. slices.SortStableFunc(kvs, func(a, b KeyValue) int { return cmp.Compare(a.Key, b.Key) }) position := len(kvs) - 1 offset := position - 1 // The requirements stated above require that the stable // result be placed in the end of the input slice, while // overwritten values are swapped to the beginning. // // De-duplicate with last-value-wins semantics. Preserve // duplicate values at the beginning of the input slice. for ; offset >= 0; offset-- { if kvs[offset].Key == kvs[position].Key { continue } position-- kvs[offset], kvs[position] = kvs[position], kvs[offset] } kvs = kvs[position:] if filter != nil { if div := filteredToFront(kvs, filter); div != 0 { return Set{equivalent: computeDistinct(kvs[div:])}, kvs[:div] } } return Set{equivalent: computeDistinct(kvs)}, nil } // NewSetWithSortableFiltered returns a new Set. // // Duplicate keys are eliminated by taking the last value. This // re-orders the input slice so that unique last-values are contiguous // at the end of the slice. // // This ensures the following: // // - Last-value-wins semantics // - Caller sees the reordering, but doesn't lose values // - Repeated call preserve last-value wins. // // Note that methods are defined on Set, although this returns Set. Callers // can avoid memory allocations by: // // - allocating a Sortable for use as a temporary in this method // - allocating a Set for storing the return value of this constructor. // // The result maintains a cache of encoded attributes, by attribute.EncoderID. // This value should not be copied after its first use. // // The second []KeyValue return value is a list of attributes that were // excluded by the Filter (if non-nil). // // Deprecated: Use [NewSetWithFiltered] instead. func NewSetWithSortableFiltered(kvs []KeyValue, _ *Sortable, filter Filter) (Set, []KeyValue) { return NewSetWithFiltered(kvs, filter) } // filteredToFront filters slice in-place using keep function. All KeyValues that need to // be removed are moved to the front. All KeyValues that need to be kept are // moved (in-order) to the back. The index for the first KeyValue to be kept is // returned. func filteredToFront(slice []KeyValue, keep Filter) int { n := len(slice) j := n for i := n - 1; i >= 0; i-- { if keep(slice[i]) { j-- slice[i], slice[j] = slice[j], slice[i] } } return j } // Filter returns a filtered copy of this Set. See the documentation for // NewSetWithSortableFiltered for more details. func (l *Set) Filter(re Filter) (Set, []KeyValue) { if re == nil { return *l, nil } // Iterate in reverse to the first attribute that will be filtered out. n := l.Len() first := n - 1 for ; first >= 0; first-- { kv, _ := l.Get(first) if !re(kv) { break } } // No attributes will be dropped, return the immutable Set l and nil. if first < 0 { return *l, nil } // Copy now that we know we need to return a modified set. // // Do not do this in-place on the underlying storage of *Set l. Sets are // immutable and filtering should not change this. slice := l.ToSlice() // Don't re-iterate the slice if only slice[0] is filtered. if first == 0 { // It is safe to assume len(slice) >= 1 given we found at least one // attribute above that needs to be filtered out. return Set{equivalent: computeDistinct(slice[1:])}, slice[:1] } // Move the filtered slice[first] to the front (preserving order). kv := slice[first] copy(slice[1:first+1], slice[:first]) slice[0] = kv // Do not re-evaluate re(slice[first+1:]). div := filteredToFront(slice[1:first+1], re) + 1 return Set{equivalent: computeDistinct(slice[div:])}, slice[:div] } // computeDistinct returns a Distinct using either the fixed- or // reflect-oriented code path, depending on the size of the input. The input // slice is assumed to already be sorted and de-duplicated. func computeDistinct(kvs []KeyValue) Distinct { iface := computeDistinctFixed(kvs) if iface == nil { iface = computeDistinctReflect(kvs) } return Distinct{ iface: iface, } } // computeDistinctFixed computes a Distinct for small slices. It returns nil // if the input is too large for this code path. func computeDistinctFixed(kvs []KeyValue) interface{} { switch len(kvs) { case 1: ptr := new([1]KeyValue) copy((*ptr)[:], kvs) return *ptr case 2: ptr := new([2]KeyValue) copy((*ptr)[:], kvs) return *ptr case 3: ptr := new([3]KeyValue) copy((*ptr)[:], kvs) return *ptr case 4: ptr := new([4]KeyValue) copy((*ptr)[:], kvs) return *ptr case 5: ptr := new([5]KeyValue) copy((*ptr)[:], kvs) return *ptr case 6: ptr := new([6]KeyValue) copy((*ptr)[:], kvs) return *ptr case 7: ptr := new([7]KeyValue) copy((*ptr)[:], kvs) return *ptr case 8: ptr := new([8]KeyValue) copy((*ptr)[:], kvs) return *ptr case 9: ptr := new([9]KeyValue) copy((*ptr)[:], kvs) return *ptr case 10: ptr := new([10]KeyValue) copy((*ptr)[:], kvs) return *ptr default: return nil } } // computeDistinctReflect computes a Distinct using reflection, works for any // size input. func computeDistinctReflect(kvs []KeyValue) interface{} { at := reflect.New(reflect.ArrayOf(len(kvs), keyValueType)).Elem() for i, keyValue := range kvs { *(at.Index(i).Addr().Interface().(*KeyValue)) = keyValue } return at.Interface() } // MarshalJSON returns the JSON encoding of the Set. func (l *Set) MarshalJSON() ([]byte, error) { return json.Marshal(l.equivalent.iface) } // MarshalLog is the marshaling function used by the logging system to represent this Set. func (l Set) MarshalLog() interface{} { kvs := make(map[string]string) for _, kv := range l.ToSlice() { kvs[string(kv.Key)] = kv.Value.Emit() } return kvs } // Len implements sort.Interface. func (l *Sortable) Len() int { return len(*l) } // Swap implements sort.Interface. func (l *Sortable) Swap(i, j int) { (*l)[i], (*l)[j] = (*l)[j], (*l)[i] } // Less implements sort.Interface. func (l *Sortable) Less(i, j int) bool { return (*l)[i].Key < (*l)[j].Key }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/attribute/value.go
vendor/go.opentelemetry.io/otel/attribute/value.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" import ( "encoding/json" "fmt" "reflect" "strconv" "go.opentelemetry.io/otel/internal" "go.opentelemetry.io/otel/internal/attribute" ) //go:generate stringer -type=Type // Type describes the type of the data Value holds. type Type int // nolint: revive // redefines builtin Type. // Value represents the value part in key-value pairs. type Value struct { vtype Type numeric uint64 stringly string slice interface{} } const ( // INVALID is used for a Value with no value set. INVALID Type = iota // BOOL is a boolean Type Value. BOOL // INT64 is a 64-bit signed integral Type Value. INT64 // FLOAT64 is a 64-bit floating point Type Value. FLOAT64 // STRING is a string Type Value. STRING // BOOLSLICE is a slice of booleans Type Value. BOOLSLICE // INT64SLICE is a slice of 64-bit signed integral numbers Type Value. INT64SLICE // FLOAT64SLICE is a slice of 64-bit floating point numbers Type Value. FLOAT64SLICE // STRINGSLICE is a slice of strings Type Value. STRINGSLICE ) // BoolValue creates a BOOL Value. func BoolValue(v bool) Value { return Value{ vtype: BOOL, numeric: internal.BoolToRaw(v), } } // BoolSliceValue creates a BOOLSLICE Value. func BoolSliceValue(v []bool) Value { return Value{vtype: BOOLSLICE, slice: attribute.BoolSliceValue(v)} } // IntValue creates an INT64 Value. func IntValue(v int) Value { return Int64Value(int64(v)) } // IntSliceValue creates an INTSLICE Value. func IntSliceValue(v []int) Value { var int64Val int64 cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(int64Val))) for i, val := range v { cp.Elem().Index(i).SetInt(int64(val)) } return Value{ vtype: INT64SLICE, slice: cp.Elem().Interface(), } } // Int64Value creates an INT64 Value. func Int64Value(v int64) Value { return Value{ vtype: INT64, numeric: internal.Int64ToRaw(v), } } // Int64SliceValue creates an INT64SLICE Value. func Int64SliceValue(v []int64) Value { return Value{vtype: INT64SLICE, slice: attribute.Int64SliceValue(v)} } // Float64Value creates a FLOAT64 Value. func Float64Value(v float64) Value { return Value{ vtype: FLOAT64, numeric: internal.Float64ToRaw(v), } } // Float64SliceValue creates a FLOAT64SLICE Value. func Float64SliceValue(v []float64) Value { return Value{vtype: FLOAT64SLICE, slice: attribute.Float64SliceValue(v)} } // StringValue creates a STRING Value. func StringValue(v string) Value { return Value{ vtype: STRING, stringly: v, } } // StringSliceValue creates a STRINGSLICE Value. func StringSliceValue(v []string) Value { return Value{vtype: STRINGSLICE, slice: attribute.StringSliceValue(v)} } // Type returns a type of the Value. func (v Value) Type() Type { return v.vtype } // AsBool returns the bool value. Make sure that the Value's type is // BOOL. func (v Value) AsBool() bool { return internal.RawToBool(v.numeric) } // AsBoolSlice returns the []bool value. Make sure that the Value's type is // BOOLSLICE. func (v Value) AsBoolSlice() []bool { if v.vtype != BOOLSLICE { return nil } return v.asBoolSlice() } func (v Value) asBoolSlice() []bool { return attribute.AsBoolSlice(v.slice) } // AsInt64 returns the int64 value. Make sure that the Value's type is // INT64. func (v Value) AsInt64() int64 { return internal.RawToInt64(v.numeric) } // AsInt64Slice returns the []int64 value. Make sure that the Value's type is // INT64SLICE. func (v Value) AsInt64Slice() []int64 { if v.vtype != INT64SLICE { return nil } return v.asInt64Slice() } func (v Value) asInt64Slice() []int64 { return attribute.AsInt64Slice(v.slice) } // AsFloat64 returns the float64 value. Make sure that the Value's // type is FLOAT64. func (v Value) AsFloat64() float64 { return internal.RawToFloat64(v.numeric) } // AsFloat64Slice returns the []float64 value. Make sure that the Value's type is // FLOAT64SLICE. func (v Value) AsFloat64Slice() []float64 { if v.vtype != FLOAT64SLICE { return nil } return v.asFloat64Slice() } func (v Value) asFloat64Slice() []float64 { return attribute.AsFloat64Slice(v.slice) } // AsString returns the string value. Make sure that the Value's type // is STRING. func (v Value) AsString() string { return v.stringly } // AsStringSlice returns the []string value. Make sure that the Value's type is // STRINGSLICE. func (v Value) AsStringSlice() []string { if v.vtype != STRINGSLICE { return nil } return v.asStringSlice() } func (v Value) asStringSlice() []string { return attribute.AsStringSlice(v.slice) } type unknownValueType struct{} // AsInterface returns Value's data as interface{}. func (v Value) AsInterface() interface{} { switch v.Type() { case BOOL: return v.AsBool() case BOOLSLICE: return v.asBoolSlice() case INT64: return v.AsInt64() case INT64SLICE: return v.asInt64Slice() case FLOAT64: return v.AsFloat64() case FLOAT64SLICE: return v.asFloat64Slice() case STRING: return v.stringly case STRINGSLICE: return v.asStringSlice() } return unknownValueType{} } // Emit returns a string representation of Value's data. func (v Value) Emit() string { switch v.Type() { case BOOLSLICE: return fmt.Sprint(v.asBoolSlice()) case BOOL: return strconv.FormatBool(v.AsBool()) case INT64SLICE: j, err := json.Marshal(v.asInt64Slice()) if err != nil { return fmt.Sprintf("invalid: %v", v.asInt64Slice()) } return string(j) case INT64: return strconv.FormatInt(v.AsInt64(), 10) case FLOAT64SLICE: j, err := json.Marshal(v.asFloat64Slice()) if err != nil { return fmt.Sprintf("invalid: %v", v.asFloat64Slice()) } return string(j) case FLOAT64: return fmt.Sprint(v.AsFloat64()) case STRINGSLICE: j, err := json.Marshal(v.asStringSlice()) if err != nil { return fmt.Sprintf("invalid: %v", v.asStringSlice()) } return string(j) case STRING: return v.stringly default: return "unknown" } } // MarshalJSON returns the JSON encoding of the Value. func (v Value) MarshalJSON() ([]byte, error) { var jsonVal struct { Type string Value interface{} } jsonVal.Type = v.Type().String() jsonVal.Value = v.AsInterface() return json.Marshal(jsonVal) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/attribute/doc.go
vendor/go.opentelemetry.io/otel/attribute/doc.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Package attribute provides key and value attributes. package attribute // import "go.opentelemetry.io/otel/attribute"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/attribute/key.go
vendor/go.opentelemetry.io/otel/attribute/key.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" // Key represents the key part in key-value pairs. It's a string. The // allowed character set in the key depends on the use of the key. type Key string // Bool creates a KeyValue instance with a BOOL Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Bool(name, value). func (k Key) Bool(v bool) KeyValue { return KeyValue{ Key: k, Value: BoolValue(v), } } // BoolSlice creates a KeyValue instance with a BOOLSLICE Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- BoolSlice(name, value). func (k Key) BoolSlice(v []bool) KeyValue { return KeyValue{ Key: k, Value: BoolSliceValue(v), } } // Int creates a KeyValue instance with an INT64 Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Int(name, value). func (k Key) Int(v int) KeyValue { return KeyValue{ Key: k, Value: IntValue(v), } } // IntSlice creates a KeyValue instance with an INT64SLICE Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- IntSlice(name, value). func (k Key) IntSlice(v []int) KeyValue { return KeyValue{ Key: k, Value: IntSliceValue(v), } } // Int64 creates a KeyValue instance with an INT64 Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Int64(name, value). func (k Key) Int64(v int64) KeyValue { return KeyValue{ Key: k, Value: Int64Value(v), } } // Int64Slice creates a KeyValue instance with an INT64SLICE Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Int64Slice(name, value). func (k Key) Int64Slice(v []int64) KeyValue { return KeyValue{ Key: k, Value: Int64SliceValue(v), } } // Float64 creates a KeyValue instance with a FLOAT64 Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Float64(name, value). func (k Key) Float64(v float64) KeyValue { return KeyValue{ Key: k, Value: Float64Value(v), } } // Float64Slice creates a KeyValue instance with a FLOAT64SLICE Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Float64(name, value). func (k Key) Float64Slice(v []float64) KeyValue { return KeyValue{ Key: k, Value: Float64SliceValue(v), } } // String creates a KeyValue instance with a STRING Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- String(name, value). func (k Key) String(v string) KeyValue { return KeyValue{ Key: k, Value: StringValue(v), } } // StringSlice creates a KeyValue instance with a STRINGSLICE Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- StringSlice(name, value). func (k Key) StringSlice(v []string) KeyValue { return KeyValue{ Key: k, Value: StringSliceValue(v), } } // Defined returns true for non-empty keys. func (k Key) Defined() bool { return len(k) != 0 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/go.opentelemetry.io/otel/attribute/encoder.go
vendor/go.opentelemetry.io/otel/attribute/encoder.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" import ( "bytes" "sync" "sync/atomic" ) type ( // Encoder is a mechanism for serializing an attribute set into a specific // string representation that supports caching, to avoid repeated // serialization. An example could be an exporter encoding the attribute // set into a wire representation. Encoder interface { // Encode returns the serialized encoding of the attribute set using // its Iterator. This result may be cached by a attribute.Set. Encode(iterator Iterator) string // ID returns a value that is unique for each class of attribute // encoder. Attribute encoders allocate these using `NewEncoderID`. ID() EncoderID } // EncoderID is used to identify distinct Encoder // implementations, for caching encoded results. EncoderID struct { value uint64 } // defaultAttrEncoder uses a sync.Pool of buffers to reduce the number of // allocations used in encoding attributes. This implementation encodes a // comma-separated list of key=value, with '/'-escaping of '=', ',', and // '\'. defaultAttrEncoder struct { // pool is a pool of attribute set builders. The buffers in this pool // grow to a size that most attribute encodings will not allocate new // memory. pool sync.Pool // *bytes.Buffer } ) // escapeChar is used to ensure uniqueness of the attribute encoding where // keys or values contain either '=' or ','. Since there is no parser needed // for this encoding and its only requirement is to be unique, this choice is // arbitrary. Users will see these in some exporters (e.g., stdout), so the // backslash ('\') is used as a conventional choice. const escapeChar = '\\' var ( _ Encoder = &defaultAttrEncoder{} // encoderIDCounter is for generating IDs for other attribute encoders. encoderIDCounter uint64 defaultEncoderOnce sync.Once defaultEncoderID = NewEncoderID() defaultEncoderInstance *defaultAttrEncoder ) // NewEncoderID returns a unique attribute encoder ID. It should be called // once per each type of attribute encoder. Preferably in init() or in var // definition. func NewEncoderID() EncoderID { return EncoderID{value: atomic.AddUint64(&encoderIDCounter, 1)} } // DefaultEncoder returns an attribute encoder that encodes attributes in such // a way that each escaped attribute's key is followed by an equal sign and // then by an escaped attribute's value. All key-value pairs are separated by // a comma. // // Escaping is done by prepending a backslash before either a backslash, equal // sign or a comma. func DefaultEncoder() Encoder { defaultEncoderOnce.Do(func() { defaultEncoderInstance = &defaultAttrEncoder{ pool: sync.Pool{ New: func() interface{} { return &bytes.Buffer{} }, }, } }) return defaultEncoderInstance } // Encode is a part of an implementation of the AttributeEncoder interface. func (d *defaultAttrEncoder) Encode(iter Iterator) string { buf := d.pool.Get().(*bytes.Buffer) defer d.pool.Put(buf) buf.Reset() for iter.Next() { i, keyValue := iter.IndexedAttribute() if i > 0 { _, _ = buf.WriteRune(',') } copyAndEscape(buf, string(keyValue.Key)) _, _ = buf.WriteRune('=') if keyValue.Value.Type() == STRING { copyAndEscape(buf, keyValue.Value.AsString()) } else { _, _ = buf.WriteString(keyValue.Value.Emit()) } } return buf.String() } // ID is a part of an implementation of the AttributeEncoder interface. func (*defaultAttrEncoder) ID() EncoderID { return defaultEncoderID } // copyAndEscape escapes `=`, `,` and its own escape character (`\`), // making the default encoding unique. func copyAndEscape(buf *bytes.Buffer, val string) { for _, ch := range val { switch ch { case '=', ',', escapeChar: _, _ = buf.WriteRune(escapeChar) } _, _ = buf.WriteRune(ch) } } // Valid returns true if this encoder ID was allocated by // `NewEncoderID`. Invalid encoder IDs will not be cached. func (id EncoderID) Valid() bool { return id.value != 0 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/vsphere_test.go
tests/suit/vsphere_test.go
package suit_test import ( "context" "time" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/kubev2v/forklift/tests/suit/framework" "github.com/kubev2v/forklift/tests/suit/utils" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) const ( vsphereProviderName = "vsphere-provider" vsphereStorageClass = "nfs-csi" ) var _ = Describe("vSphere provider", func() { f := framework.NewFramework("migration-func-test") It("Migrate VM", func() { namespace := f.Namespace.Name By("Create Secret from Definition") simSecret, err := utils.GetSecret(f.K8sClient, "konveyor-forklift", "vcsim-certificate") Expect(err).ToNot(HaveOccurred()) s, err := utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition(nil, nil, map[string][]byte{ "cacert": simSecret.Data["ca.crt"], "password": []byte("MTIzNDU2Cg=="), "user": []byte("YWRtaW5pc3RyYXRvckB2c3BoZXJlLmxvY2Fs"), }, namespace, "provider-test-secret")) Expect(err).ToNot(HaveOccurred()) targetNS, err := f.CreateNamespace("default", map[string]string{}) Expect(err).ToNot(HaveOccurred()) By("Create target Openshift provider") targetPr := utils.NewProvider(utils.TargetProviderName, forkliftv1.OpenShift, namespace, map[string]string{}, map[string]string{}, "", nil) err = utils.CreateProviderFromDefinition(f.CrClient, targetPr) Expect(err).ToNot(HaveOccurred()) _, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, utils.TargetProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create vSphere provider") pr := utils.NewProvider(vsphereProviderName, forkliftv1.VSphere, namespace, map[string]string{}, map[string]string{forkliftv1.VDDK: "quay.io/kubev2v/vddk-test-vmdk"}, "https://vcsim.konveyor-forklift:8989/sdk", s) err = utils.CreateProviderFromDefinition(f.CrClient, pr) Expect(err).ToNot(HaveOccurred()) provider, err := utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, vsphereProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Network Map") networkMapDef := utils.NewNetworkMap(namespace, *provider, networkMapName, "dvportgroup-13") err = utils.CreateNetworkMapFromDefinition(f.CrClient, networkMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForNetworkMapReadyWithTimeout(f.CrClient, namespace, networkMapName, 10*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Storage Map") storageMapDef := utils.NewStorageMap(namespace, *provider, test_storage_map_name, []string{"datastore-52"}, vsphereStorageClass) err = utils.CreateStorageMapFromDefinition(f.CrClient, storageMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForStorageMapReadyWithTimeout(f.CrClient, namespace, test_storage_map_name, 10*time.Second) Expect(err).ToNot(HaveOccurred()) By("Creating plan") planDef := utils.NewPlanWithVmName(*provider, namespace, test_plan_name, test_storage_map_name, networkMapName, []string{"DC0_H0_VM0"}, targetNS.Name) err = utils.CreatePlanFromDefinition(f.CrClient, planDef) Expect(err).ToNot(HaveOccurred()) err, _ = utils.WaitForPlanReadyWithTimeout(f.CrClient, namespace, test_plan_name, 1*time.Minute) Expect(err).ToNot(HaveOccurred()) By("Creating migration") migrationDef := utils.NewMigration(provider.Namespace, test_migration_name, test_plan_name) err = utils.CreateMigrationFromDefinition(f.CrClient, migrationDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForMigrationSucceededWithTimeout(f.CrClient, provider.Namespace, test_migration_name, 300*time.Second) Expect(err).ToNot(HaveOccurred()) }) Context("vCenter SDK", func() { var provider *forkliftv1.Provider var namespace string BeforeEach(func() { namespace = f.Namespace.Name By("Create Secret from Definition") s, err := utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition(nil, nil, map[string][]byte{ v1beta1.Insecure: []byte("true"), "password": []byte("MTIzNDU2Cg=="), "user": []byte("YWRtaW5pc3RyYXRvckB2c3BoZXJlLmxvY2Fs"), }, namespace, "vcenter-provider-secret")) Expect(err).ToNot(HaveOccurred()) By("Create vCenter provider") pr := utils.NewProvider(vsphereProviderName, forkliftv1.VSphere, namespace, map[string]string{}, map[string]string{forkliftv1.VDDK: "quay.io/kubev2v/vddk-test-vmdk"}, "https://vcsim.konveyor-forklift:8989/sdk", s) err = utils.CreateProviderFromDefinition(f.CrClient, pr) Expect(err).ToNot(HaveOccurred()) provider, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, vsphereProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) }) It("Provider should be set with sdkEndpoint=vcenter by default", func() { Expect(provider.Spec.Settings[forkliftv1.SDK]).To(Equal(forkliftv1.VCenter)) }) It("Host cannot be defined with empty credentials", func() { labels := map[string]string{ "createdForResourceType": "hosts", "createdForResource": "host-21", } _, err := utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition(labels, nil, map[string][]byte{ "ip": []byte("52:6C:4E:88:1D:78:AE:12:1C:F3:BB:6C:5B:F4:E2:82:86:A7:08:AF"), "provider": []byte(vsphereProviderName), }, namespace, "esxi-host-secret")) Expect(err).To(HaveOccurred()) }) }) Context("ESXi SDK", func() { var provider *forkliftv1.Provider var namespace string BeforeEach(func() { namespace = f.Namespace.Name By("Create Secret from Definition") s, err := utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition(nil, nil, map[string][]byte{ v1beta1.Insecure: []byte("true"), "password": []byte("MTIzNDU2Cg=="), "user": []byte("YWRtaW5pc3RyYXRvckB2c3BoZXJlLmxvY2Fs"), }, namespace, "esxi-provider-secret")) Expect(err).ToNot(HaveOccurred()) By("Create ESXi provider") settings := map[string]string{ forkliftv1.VDDK: "quay.io/kubev2v/vddk-test-vmdk", forkliftv1.SDK: forkliftv1.ESXI, } pr := utils.NewProvider(vsphereProviderName, forkliftv1.VSphere, namespace, map[string]string{}, settings, "https://vcsim.konveyor-forklift:8989/sdk", s) err = utils.CreateProviderFromDefinition(f.CrClient, pr) Expect(err).ToNot(HaveOccurred()) provider, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, vsphereProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) }) It("Provider should be set with sdkEndpoint=esxi", func() { Expect(provider.Spec.Settings[forkliftv1.SDK]).To(Equal(forkliftv1.ESXI)) }) It("Credentials are copied from the Provider to the Host", func() { labels := map[string]string{ "createdForResourceType": "hosts", "createdForResource": "host-21", } secret := utils.NewSecretDefinition(labels, nil, map[string][]byte{ "ip": []byte("52:6C:4E:88:1D:78:AE:12:1C:F3:BB:6C:5B:F4:E2:82:86:A7:08:AF"), "provider": []byte(vsphereProviderName), }, namespace, "esxi-host-secret", ) secret, err := f.K8sClient.CoreV1().Secrets(secret.Namespace).Create(context.TODO(), secret, metav1.CreateOptions{}) Expect(err).ToNot(HaveOccurred()) _, found := secret.Data["user"] Expect(found).To(BeTrue()) }) }) })
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/forklift_test.go
tests/suit/forklift_test.go
package suit_test import ( "time" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/kubev2v/forklift/tests/suit/framework" "github.com/kubev2v/forklift/tests/suit/utils" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" v1 "k8s.io/api/core/v1" ) const ( AnnPopulatorLabels = "populatorLabels" ) var _ = Describe("Forklift", func() { f := framework.NewFramework("migration-func-test") var vmData *framework.OvirtVM var secret *v1.Secret var namespace string BeforeEach(func() { namespace = f.Namespace.Name err := f.Clients.OvirtClient.SetupClient(false) Expect(err).ToNot(HaveOccurred()) By("Load Source VM Details from Ovirt") vmData, err = f.Clients.OvirtClient.LoadSourceDetails() Expect(err).ToNot(HaveOccurred()) By("Create Secret from Definition") secret, err = utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition( map[string]string{ "createdForProviderType": "ovirt", }, nil, map[string][]byte{ "cacert": []byte(f.OvirtClient.Cacert), "password": []byte(f.OvirtClient.Password), "user": []byte(f.OvirtClient.Username), "url": []byte(f.OvirtClient.OvirtURL), }, namespace, "provider-test-secret")) Expect(err).ToNot(HaveOccurred()) }) Context("Plan with provider that is set with transfer network", func() { providerNetwork := "my-network" var provider *forkliftv1.Provider var targetNS *v1.Namespace var err error BeforeEach(func() { targetNS, err = f.CreateNamespace("target", map[string]string{}) Expect(err).ToNot(HaveOccurred()) By("Create target Openshift provider") annotations := map[string]string{"forklift.konveyor.io/defaultTransferNetwork": providerNetwork} target := utils.NewProvider(utils.TargetProviderName, forkliftv1.OpenShift, namespace, annotations, map[string]string{}, "", nil) err = utils.CreateProviderFromDefinition(f.CrClient, target) Expect(err).ToNot(HaveOccurred()) _, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, utils.TargetProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create oVirt provider") pr := utils.NewProvider(ovirtProviderName, forkliftv1.OVirt, namespace, map[string]string{}, map[string]string{}, f.OvirtClient.OvirtURL, secret) err = utils.CreateProviderFromDefinition(f.CrClient, pr) Expect(err).ToNot(HaveOccurred()) provider, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, ovirtProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Network Map") networkMapDef := utils.NewNetworkMap(namespace, *provider, networkMapName, vmData.GetVMNics()[0]) err = utils.CreateNetworkMapFromDefinition(f.CrClient, networkMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForNetworkMapReadyWithTimeout(f.CrClient, namespace, networkMapName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Storage Map") storageMapDef := utils.NewStorageMap(namespace, *provider, test_storage_map_name, vmData.GetVMSDs(), ovirtStorageClass) err = utils.CreateStorageMapFromDefinition(f.CrClient, storageMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForStorageMapReadyWithTimeout(f.CrClient, namespace, test_storage_map_name, 30*time.Second) Expect(err).ToNot(HaveOccurred()) }) It("Transfer network should not be set to that of the Provider when it doesn't exist", func() { By("Create plan") planDef := utils.NewPlanWithVmId(*provider, namespace, test_plan_name, test_storage_map_name, networkMapName, targetNS.Name, []string{vmData.GetTestVMId()}) err = utils.CreatePlanFromDefinition(f.CrClient, planDef) Expect(err).ToNot(HaveOccurred()) err, plan := utils.WaitForPlanReadyWithTimeout(f.CrClient, namespace, planDef.Name, 15*time.Second) Expect(err).ToNot(HaveOccurred()) By("Verify created plan") Expect(plan).ToNot(BeNil()) Expect(plan.Spec.TransferNetwork).To(BeNil()) }) It("Transfer network should be set to that of the Provider when it exists", func() { By("Create Network Attachment Definition") err, _ = utils.CreateNetworkAttachmentDefinition(f.CrClient, providerNetwork, targetNS.Name) Expect(err).ToNot(HaveOccurred()) By("Create plan") planDef := utils.NewPlanWithVmId(*provider, namespace, test_plan_name, test_storage_map_name, networkMapName, targetNS.Name, []string{vmData.GetTestVMId()}) err = utils.CreatePlanFromDefinition(f.CrClient, planDef) Expect(err).ToNot(HaveOccurred()) err, plan := utils.WaitForPlanReadyWithTimeout(f.CrClient, namespace, planDef.Name, 15*time.Second) Expect(err).ToNot(HaveOccurred()) By("Verify created plan") Expect(plan).ToNot(BeNil()) Expect(plan.Spec.TransferNetwork).ToNot(BeNil()) Expect(plan.Spec.TransferNetwork.Name).To(Equal(providerNetwork)) }) It("Transfer network should not be overridden with that of the provider when specified", func() { By("Create Network Attachment Definition") err, nad := utils.CreateNetworkAttachmentDefinition(f.CrClient, providerNetwork, targetNS.Name) Expect(err).ToNot(HaveOccurred()) By("Create plan with other transfer network") planDef := utils.NewPlanWithVmId(*provider, namespace, test_plan_name, test_storage_map_name, networkMapName, targetNS.Name, []string{vmData.GetTestVMId()}) planNetwork := "another-network" planDef.Spec.TransferNetwork = &v1.ObjectReference{ Namespace: nad.Namespace, Name: planNetwork, } err = utils.CreatePlanFromDefinition(f.CrClient, planDef) Expect(err).ToNot(HaveOccurred()) By("Get created plan") err, plan := utils.GetPlan(f.CrClient, planDef.Namespace, planDef.Name) Expect(err).ToNot(HaveOccurred()) By("Verify created plan") Expect(plan).ToNot(BeNil()) Expect(plan.Spec.TransferNetwork).ToNot(BeNil()) Expect(plan.Spec.TransferNetwork.Name).To(Equal(planNetwork)) }) It("Annotation of new plan should be set with populator labels annotation true", func() { By("Create plan") planDef := utils.NewPlanWithVmId(*provider, namespace, test_plan_name, test_storage_map_name, networkMapName, targetNS.Name, []string{vmData.GetTestVMId()}) err = utils.CreatePlanFromDefinition(f.CrClient, planDef) Expect(err).ToNot(HaveOccurred()) err, plan := utils.WaitForPlanReadyWithTimeout(f.CrClient, namespace, planDef.Name, 15*time.Second) Expect(err).ToNot(HaveOccurred()) By("Verify created plan") Expect(plan).ToNot(BeNil()) Expect(plan.Annotations[AnnPopulatorLabels]).To(Equal("True")) }) }) Context("Plan with provider that is set with transfer network that includes namespace", func() { providerNetworkNamespace := "default" providerNetworkName := "my-network" providerNetwork := providerNetworkNamespace + "/" + providerNetworkName var provider *forkliftv1.Provider var targetNS *v1.Namespace var err error BeforeEach(func() { targetNS, err = f.CreateNamespace("target", map[string]string{}) Expect(err).ToNot(HaveOccurred()) targetNS, err = f.CreateNamespace(providerNetworkNamespace, map[string]string{}) Expect(err).ToNot(HaveOccurred()) By("Create target Openshift provider") annotations := map[string]string{"forklift.konveyor.io/defaultTransferNetwork": providerNetwork} target := utils.NewProvider(utils.TargetProviderName, forkliftv1.OpenShift, namespace, annotations, map[string]string{}, "", nil) err = utils.CreateProviderFromDefinition(f.CrClient, target) Expect(err).ToNot(HaveOccurred()) _, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, utils.TargetProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create oVirt provider") pr := utils.NewProvider(ovirtProviderName, forkliftv1.OVirt, namespace, map[string]string{}, map[string]string{}, f.OvirtClient.OvirtURL, secret) err = utils.CreateProviderFromDefinition(f.CrClient, pr) Expect(err).ToNot(HaveOccurred()) provider, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, ovirtProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Network Map") networkMapDef := utils.NewNetworkMap(namespace, *provider, networkMapName, vmData.GetVMNics()[0]) err = utils.CreateNetworkMapFromDefinition(f.CrClient, networkMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForNetworkMapReadyWithTimeout(f.CrClient, namespace, networkMapName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Storage Map") storageMapDef := utils.NewStorageMap(namespace, *provider, test_storage_map_name, vmData.GetVMSDs(), ovirtStorageClass) err = utils.CreateStorageMapFromDefinition(f.CrClient, storageMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForStorageMapReadyWithTimeout(f.CrClient, namespace, test_storage_map_name, 30*time.Second) Expect(err).ToNot(HaveOccurred()) }) It("Namespaced transfer network should not be set to that of the Provider when it doesn't exist", func() { By("Create plan for provider with defaultTransferNetwork") planDef := utils.NewPlanWithVmId(*provider, namespace, test_plan_name, test_storage_map_name, networkMapName, targetNS.Name, []string{vmData.GetTestVMId()}) err = utils.CreatePlanFromDefinition(f.CrClient, planDef) Expect(err).ToNot(HaveOccurred()) err, plan := utils.WaitForPlanReadyWithTimeout(f.CrClient, namespace, planDef.Name, 15*time.Second) Expect(err).ToNot(HaveOccurred()) By("Verify created plan") Expect(plan).ToNot(BeNil()) Expect(plan.Spec.TransferNetwork).To(BeNil()) }) It("Namespaced transfer network should be set to that of the Provider when it exists", func() { By("Create namespaced Network Attachment Definition") err, _ = utils.CreateNetworkAttachmentDefinition(f.CrClient, providerNetworkName, providerNetworkNamespace) Expect(err).ToNot(HaveOccurred()) By("Create plan for provider with defaultTransferNetwork") planDef := utils.NewPlanWithVmId(*provider, namespace, test_plan_name, test_storage_map_name, networkMapName, targetNS.Name, []string{vmData.GetTestVMId()}) err = utils.CreatePlanFromDefinition(f.CrClient, planDef) Expect(err).ToNot(HaveOccurred()) err, plan := utils.WaitForPlanReadyWithTimeout(f.CrClient, namespace, planDef.Name, 15*time.Second) Expect(err).ToNot(HaveOccurred()) By("Verify created plan for provider with defaultTransferNetwork") Expect(plan).ToNot(BeNil()) Expect(plan.Spec.TransferNetwork).ToNot(BeNil()) Expect(plan.Spec.TransferNetwork.Name).To(Equal(providerNetworkName)) Expect(plan.Spec.TransferNetwork.Namespace).To(Equal(providerNetworkNamespace)) }) }) })
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/openstack_test.go
tests/suit/openstack_test.go
package suit_test import ( "time" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref" "github.com/kubev2v/forklift/tests/suit/framework" "github.com/kubev2v/forklift/tests/suit/utils" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( openstackProviderName = "osp-provider" openstackStorageClass = "nfs-csi" packstackNameSpace = "konveyor-forklift" ) var _ = Describe("[level:component]Migration tests for OpenStack provider", func() { f := framework.NewFramework("migration-func-test") It("[test] should create provider with NetworkMap", func() { namespace := f.Namespace.Name err := f.Clients.OpenStackClient.SetupClient("cirros-server", "net-int", "nfs") Expect(err).ToNot(HaveOccurred()) By("Load Source VM Details from OpenStack") vmData, err := f.Clients.OpenStackClient.LoadSourceDetails(f, packstackNameSpace, "packstack") Expect(err).ToNot(HaveOccurred()) By("Create Secret from Definition") s, err := utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition(nil, map[string]string{ "username": "admin", "password": "12e2f14739194a6c", "domainName": "default", "projectName": "admin", "regionName": "RegionOne", "insecureSkipVerify": "true", }, nil, namespace, "os-test-secret")) Expect(err).ToNot(HaveOccurred()) By("Create target Openshift provider") targetPr := utils.NewProvider(utils.TargetProviderName, forkliftv1.OpenShift, namespace, map[string]string{}, map[string]string{}, "", nil) err = utils.CreateProviderFromDefinition(f.CrClient, targetPr) Expect(err).ToNot(HaveOccurred()) _, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, utils.TargetProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create osp provider") pr := utils.NewProvider(openstackProviderName, forkliftv1.OpenStack, namespace, map[string]string{}, map[string]string{}, "http://packstack.konveyor-forklift:5000/v3", s) err = utils.CreateProviderFromDefinition(f.CrClient, pr) Expect(err).ToNot(HaveOccurred()) provider, err := utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, openstackProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) networkMapDef := utils.NewNetworkMap(namespace, *provider, networkMapName, vmData.GetNetworkId()) err = utils.CreateNetworkMapFromDefinition(f.CrClient, networkMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForNetworkMapReadyWithTimeout(f.CrClient, namespace, networkMapName, 10*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Storage Map") //TODO: Add storage-class pass here storageMapDef := utils.NewStorageMap(namespace, *provider, test_storage_map_name, []string{vmData.GetVolumeId()}, openstackStorageClass) storageMapDef.Spec.Map = append(storageMapDef.Spec.Map, forkliftv1.StoragePair{ Source: ref.Ref{Name: forkliftv1.GlanceSource}, Destination: forkliftv1.DestinationStorage{ StorageClass: openstackStorageClass, }, }) err = utils.CreateStorageMapFromDefinition(f.CrClient, storageMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForStorageMapReadyWithTimeout(f.CrClient, namespace, test_storage_map_name, 10*time.Second) Expect(err).ToNot(HaveOccurred()) By("Creating plan") planDef := utils.NewPlanWithVmId(*provider, namespace, test_plan_name, test_storage_map_name, networkMapName, namespace, []string{vmData.GetTestVMId()}) planDef.Spec.Warm = true err = utils.CreatePlanFromDefinition(f.CrClient, planDef) Expect(err).To(HaveOccurred()) planDef.Spec.Warm = false err = utils.CreatePlanFromDefinition(f.CrClient, planDef) Expect(err).ToNot(HaveOccurred()) err = utils.UpdatePlanWarmMigration(f.CrClient, planDef, true) Expect(err).To(HaveOccurred()) err, _ = utils.WaitForPlanReadyWithTimeout(f.CrClient, namespace, test_plan_name, 15*time.Second) Expect(err).ToNot(HaveOccurred()) By("Creating migration") migrationDef := utils.NewMigration(provider.Namespace, test_migration_name, test_plan_name) err = utils.CreateMigrationFromDefinition(f.CrClient, migrationDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForMigrationSucceededWithTimeout(f.CrClient, provider.Namespace, test_migration_name, 400*time.Second) Expect(err).ToNot(HaveOccurred()) }) })
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/openstack_extended_test.go
tests/suit/openstack_extended_test.go
//nolint:errcheck package suit_test import ( "github.com/kubev2v/forklift/pkg/lib/client/openstack" "github.com/kubev2v/forklift/pkg/lib/logging" "github.com/kubev2v/forklift/tests/suit/framework" "github.com/kubev2v/forklift/tests/suit/utils" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( keystoneSecureURL = "https://packstack.konveyor-forklift:30051/v3" ) var _ = Describe("[level:component]Migration Extended tests for OpenStack provider", func() { f := framework.NewFramework("migration-func-test") It("[extended] should connect to openstack using https/ssl with CA", func() { namespace := f.Namespace.Name err := f.Clients.OpenStackClient.SetupClient("cirros-volume", "net-int", "nfs") Expect(err).ToNot(HaveOccurred()) By("Load Source VM Details from OpenStack") packstackCA, err := f.Clients.OpenStackClient.LoadCA(f, packstackNameSpace, "packstack") Expect(err).ToNot(HaveOccurred()) err = utils.TestHttpsCA(keystoneSecureURL, packstackCA, false) Expect(err).ToNot(HaveOccurred()) By("Create Secret from Definition") clientOpts := map[string]string{ "username": "admin", "password": "12e2f14739194a6c", "domainName": "default", "projectName": "admin", "regionName": "RegionOne", "cacert": packstackCA, } _, err = utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition(nil, clientOpts, nil, namespace, "os-test-secret")) Expect(err).ToNot(HaveOccurred()) client := openstack.Client{ URL: keystoneSecureURL, Options: clientOpts, Log: logging.WithName("test"), } err = client.Connect() Expect(err).ToNot(HaveOccurred()) }) It("[test] should connect to openstack using https/ssl insecure", func() { namespace := f.Namespace.Name err := f.Clients.OpenStackClient.SetupClient("cirros-volume", "net-int", "nfs") Expect(err).ToNot(HaveOccurred()) By("Create Secret from Definition") clientOpts := map[string]string{ "username": "admin", "password": "12e2f14739194a6c", "domainName": "default", "projectName": "admin", "regionName": "RegionOne", "insecureSkipVerify": "true", "cacert": "", } _, err = utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition(nil, clientOpts, nil, namespace, "os-test-secret")) Expect(err).ToNot(HaveOccurred()) client := openstack.Client{ URL: keystoneSecureURL, Options: clientOpts, Log: logging.WithName("test"), } err = client.Connect() Expect(err).ToNot(HaveOccurred()) }) It("[test] should connect to openstack using https/ssl with system CA", func() { namespace := f.Namespace.Name err := f.Clients.OpenStackClient.SetupClient("cirros-volume", "net-int", "nfs") Expect(err).ToNot(HaveOccurred()) By("Load Source VM Details from OpenStack") packstackCA, err := f.Clients.OpenStackClient.LoadCA(f, packstackNameSpace, "packstack") Expect(err).ToNot(HaveOccurred()) err = utils.UpdateLocalCA(packstackCA) Expect(err).ToNot(HaveOccurred()) err = utils.TestHttpsCA(keystoneSecureURL, packstackCA, false) Expect(err).ToNot(HaveOccurred()) By("Create Secret from Definition") clientOpts := map[string]string{ "username": "admin", "password": "12e2f14739194a6c", "domainName": "default", "projectName": "admin", "regionName": "RegionOne", "cacert": "", } _, err = utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition(nil, clientOpts, nil, namespace, "os-test-secret")) Expect(err).ToNot(HaveOccurred()) client := openstack.Client{ URL: keystoneSecureURL, Options: clientOpts, Log: logging.WithName("test"), } err = client.Connect() Expect(err).ToNot(HaveOccurred()) utils.RemoveLocalCA() }) It("[test] should not connect with invalid CA and not fallback to system", func() { namespace := f.Namespace.Name err := f.Clients.OpenStackClient.SetupClient("cirros-volume", "net-int", "nfs") Expect(err).ToNot(HaveOccurred()) By("Load Source VM Details from OpenStack") packstackCA, err := f.Clients.OpenStackClient.LoadCA(f, packstackNameSpace, "packstack") Expect(err).ToNot(HaveOccurred()) err = utils.UpdateLocalCA(packstackCA) Expect(err).ToNot(HaveOccurred()) err = utils.TestHttpsCA(keystoneSecureURL, packstackCA, false) Expect(err).ToNot(HaveOccurred()) By("Create Secret from Definition") clientOpts := map[string]string{ "username": "admin", "password": "12e2f14739194a6c", "domainName": "default", "projectName": "admin", "regionName": "RegionOne", "cacert": packstackCA + "bad", } _, err = utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition(nil, clientOpts, nil, namespace, "os-test-secret")) Expect(err).ToNot(HaveOccurred()) client := openstack.Client{ URL: keystoneSecureURL, Options: clientOpts, Log: logging.WithName("test"), } err = client.Connect() Expect(err).To(HaveOccurred()) utils.RemoveLocalCA() }) })
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/ova_test.go
tests/suit/ova_test.go
package suit_test import ( "time" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/kubev2v/forklift/tests/suit/framework" "github.com/kubev2v/forklift/tests/suit/utils" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( ovaProviderName = "ova-provider" ovaStorageClass = "nfs-csi" ) var _ = Describe("[level:component]Migration tests for OVA provider", func() { f := framework.NewFramework("migration-func-test") It("[test] should create provider with NetworkMap", func() { namespace := f.Namespace.Name By("Load Source VM Details from OVA") vmData, err := f.Clients.OvaClient.LoadSourceDetails() Expect(err).ToNot(HaveOccurred()) By("Get NFS share for OVA provider") nfs, err := f.Clients.OvaClient.GetNfsServerForOva(f.K8sClient) Expect(err).ToNot(HaveOccurred()) By("Create Secret from Definition") secret, err := utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition( map[string]string{ "createdForProviderType": "ova", "createdForResourceType": "providers", }, nil, map[string][]byte{ "url": []byte(nfs), }, namespace, "provider-test-secret")) Expect(err).ToNot(HaveOccurred()) targetNS, err := f.CreateNamespace("ova-migration-test", map[string]string{}) Expect(err).ToNot(HaveOccurred()) By("Create target Openshift provider") targetPr := utils.NewProvider(utils.TargetProviderName, forkliftv1.OpenShift, namespace, map[string]string{}, map[string]string{}, "", nil) err = utils.CreateProviderFromDefinition(f.CrClient, targetPr) Expect(err).ToNot(HaveOccurred()) _, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, utils.TargetProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create OVA provider") pr := utils.NewProvider(ovaProviderName, forkliftv1.Ova, namespace, map[string]string{}, map[string]string{}, nfs, secret) err = utils.CreateProviderFromDefinition(f.CrClient, pr) Expect(err).ToNot(HaveOccurred()) provider, err := utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, ovaProviderName, 5*time.Minute) Expect(err).ToNot(HaveOccurred()) By("Create Network Map") networkMapDef := utils.NewNetworkMap(namespace, *provider, networkMapName, vmData.GetNetworkId()) err = utils.CreateNetworkMapFromDefinition(f.CrClient, networkMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForNetworkMapReadyWithTimeout(f.CrClient, namespace, networkMapName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Storage Map") storageMapDef := utils.NewStorageMap(namespace, *provider, test_storage_map_name, []string{vmData.GetStorageName()}, ovaStorageClass) err = utils.CreateStorageMapFromDefinition(f.CrClient, storageMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForStorageMapReadyWithTimeout(f.CrClient, namespace, test_storage_map_name, 10*time.Second) Expect(err).ToNot(HaveOccurred()) By("Creating plan") planDef := utils.NewPlanWithVmName(*provider, namespace, test_plan_name, test_storage_map_name, networkMapName, []string{vmData.GetVmName()}, targetNS.Name) err = utils.CreatePlanFromDefinition(f.CrClient, planDef) Expect(err).ToNot(HaveOccurred()) err, _ = utils.WaitForPlanReadyWithTimeout(f.CrClient, namespace, test_plan_name, 15*time.Second) Expect(err).ToNot(HaveOccurred()) By("Creating migration") migrationDef := utils.NewMigration(provider.Namespace, test_migration_name, test_plan_name) err = utils.CreateMigrationFromDefinition(f.CrClient, migrationDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForMigrationSucceededWithTimeout(f.CrClient, provider.Namespace, test_migration_name, 900*time.Second) Expect(err).ToNot(HaveOccurred()) }) })
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/tests_suite_test.go
tests/suit/tests_suite_test.go
package suit_test import ( "flag" "fmt" "testing" "github.com/kubev2v/forklift/tests/suit/framework" "github.com/kubev2v/forklift/tests/suit/utils" "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( networkMapName = "network-map-test" test_migration_name = "migration-test" test_plan_name = "plan-test" test_storage_map_name = "test-storage-map-v" test_network_map_name_insecure = "network-map-test-insecure" test_migration_name_insecure = "migration-test-insecure" test_plan_name_insecure = "plan-test-insecure" test_storage_map_name_insecure = "test-storage-map-insecure" ) var ( kubectlPath = flag.String("kubectl-path", "kubectl", "The path to the kubectl binary") ocPath = flag.String("oc-path", "oc", "The path to the oc binary") forkliftInstallNs = flag.String("forklift-namespace", "konveyor-forklift", "The namespace of the CDI controller") kubeConfig = flag.String("kubeconfig2", "/tmp/kubeconfig", "The absolute path to the kubeconfig file") kubeURL = flag.String("kubeurl", "", "kube URL url:port") goCLIPath = flag.String("gocli-path", "cli.sh", "The path to cli script") dockerPrefix = flag.String("docker-prefix", "", "The docker host:port") dockerTag = flag.String("docker-tag", "", "The docker tag") deleteNameSpace = flag.Bool("delete-namespace", false, "Delete namespace after completion") ) // forkliftFailHandler call ginkgo.Fail with printing the additional information func forkliftFailHandler(message string, callerSkip ...int) { if len(callerSkip) > 0 { callerSkip[0]++ } ginkgo.Fail(message, callerSkip...) } func TestTests(t *testing.T) { defer GinkgoRecover() RegisterFailHandler(forkliftFailHandler) BuildTestSuite() RunSpecs(t, "Tests Suite") } // To understand the order in which things are run, read http://onsi.github.io/ginkgo/#understanding-ginkgos-lifecycle // flag parsing happens AFTER ginkgo has constructed the entire testing tree. So anything that uses information from flags // cannot work when called during test tree construction. func BuildTestSuite() { BeforeSuite(func() { fmt.Fprintf(ginkgo.GinkgoWriter, "Reading parameters\n") // Read flags, and configure client instances framework.ClientsInstance.KubectlPath = *kubectlPath framework.ClientsInstance.OcPath = *ocPath framework.ClientsInstance.ForkliftInstallNs = *forkliftInstallNs framework.ClientsInstance.KubeConfig = *kubeConfig framework.ClientsInstance.KubeURL = *kubeURL framework.ClientsInstance.GoCLIPath = *goCLIPath framework.ClientsInstance.DockerPrefix = *dockerPrefix framework.ClientsInstance.DockerTag = *dockerTag framework.ClientsInstance.AutoDeleteNs = *deleteNameSpace fmt.Fprintf(ginkgo.GinkgoWriter, "Kubectl path: %s\n", framework.ClientsInstance.KubectlPath) fmt.Fprintf(ginkgo.GinkgoWriter, "OC path: %s\n", framework.ClientsInstance.OcPath) fmt.Fprintf(ginkgo.GinkgoWriter, "Forklift install NS: %s\n", framework.ClientsInstance.ForkliftInstallNs) fmt.Fprintf(ginkgo.GinkgoWriter, "Kubeconfig: %s\n", framework.ClientsInstance.KubeConfig) fmt.Fprintf(ginkgo.GinkgoWriter, "KubeURL: %s\n", framework.ClientsInstance.KubeURL) fmt.Fprintf(ginkgo.GinkgoWriter, "GO CLI path: %s\n", framework.ClientsInstance.GoCLIPath) fmt.Fprintf(ginkgo.GinkgoWriter, "DockerPrefix: %s\n", framework.ClientsInstance.DockerPrefix) fmt.Fprintf(ginkgo.GinkgoWriter, "DockerTag: %s\n", framework.ClientsInstance.DockerTag) restConfig, err := framework.ClientsInstance.LoadConfig() if err != nil { // Can't use Expect here due this being called outside of an It block, and Expect // requires any calls to it to be inside an It block. ginkgo.Fail("ERROR, unable to load RestConfig") } framework.ClientsInstance.RestConfig = restConfig // clients kcs, err := framework.ClientsInstance.GetKubeClient() if err != nil { ginkgo.Fail(fmt.Sprintf("ERROR, unable to create K8SClient: %v", err)) } framework.ClientsInstance.K8sClient = kcs crClient, err := framework.ClientsInstance.GetCrClient() if err != nil { ginkgo.Fail(fmt.Sprintf("ERROR, unable to create CrClient: %v", err)) } framework.ClientsInstance.CrClient = crClient dyn, err := framework.ClientsInstance.GetDynamicClient() if err != nil { ginkgo.Fail(fmt.Sprintf("ERROR, unable to create DynamicClient: %v", err)) } framework.ClientsInstance.DynamicClient = dyn utils.CacheTestsData(framework.ClientsInstance.K8sClient, framework.ClientsInstance.ForkliftInstallNs) ovirtClient, err := framework.ClientsInstance.GetOvirtClient() if err != nil { ginkgo.Fail(fmt.Sprintf("ERROR, unable to create OvirtClient: %v", err)) } framework.ClientsInstance.OvirtClient = *ovirtClient openStackClient, err := framework.ClientsInstance.GetOpenStackClient() if err != nil { ginkgo.Fail(fmt.Sprintf("ERROR, unable to create OpenStackClient: %v", err)) } framework.ClientsInstance.OpenStackClient = *openStackClient }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/ovirt_test.go
tests/suit/ovirt_test.go
package suit_test import ( "strconv" "time" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/kubev2v/forklift/tests/suit/framework" "github.com/kubev2v/forklift/tests/suit/utils" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/apimachinery/pkg/types" cnv "kubevirt.io/api/core/v1" ) const ( ovirtProviderName = "ovirt-provider" ovirtInsecureProviderName = "ovirt-provider-insecure" ovirtStorageClass = "nfs-csi" clusterCpuModel = "Westmere" ) var _ = Describe("[level:component]Migration tests for oVirt providers", func() { f := framework.NewFramework("migration-func-test") Context("[oVirt MTV] should create secure provider", func() { It("secure flow", func() { namespace := f.Namespace.Name err := f.Clients.OvirtClient.SetupClient(false) Expect(err).ToNot(HaveOccurred()) By("Load Source VM Details from Ovirt") vmData, err := f.Clients.OvirtClient.LoadSourceDetails() Expect(err).ToNot(HaveOccurred()) By("Create Secret from Definition") s, err := utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition( map[string]string{ "createdForProviderType": "ovirt", }, nil, map[string][]byte{ "cacert": []byte(f.OvirtClient.Cacert), "password": []byte(f.OvirtClient.Password), "user": []byte(f.OvirtClient.Username), "url": []byte(f.OvirtClient.OvirtURL), }, namespace, "provider-test-secret")) Expect(err).ToNot(HaveOccurred()) targetNS, err := f.CreateNamespace("default", map[string]string{}) Expect(err).ToNot(HaveOccurred()) By("Create target Openshift provider") targetPr := utils.NewProvider(utils.TargetProviderName, forkliftv1.OpenShift, namespace, map[string]string{}, map[string]string{}, "", nil) err = utils.CreateProviderFromDefinition(f.CrClient, targetPr) Expect(err).ToNot(HaveOccurred()) _, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, utils.TargetProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create oVirt provider") pr := utils.NewProvider(ovirtProviderName, forkliftv1.OVirt, namespace, map[string]string{}, map[string]string{}, f.OvirtClient.OvirtURL, s) err = utils.CreateProviderFromDefinition(f.CrClient, pr) Expect(err).ToNot(HaveOccurred()) provider, err := utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, ovirtProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Network Map") networkMapDef := utils.NewNetworkMap(namespace, *provider, networkMapName, vmData.GetVMNics()[0]) err = utils.CreateNetworkMapFromDefinition(f.CrClient, networkMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForNetworkMapReadyWithTimeout(f.CrClient, namespace, networkMapName, 10*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Storage Map") storageMapDef := utils.NewStorageMap(namespace, *provider, test_storage_map_name, vmData.GetVMSDs(), ovirtStorageClass) err = utils.CreateStorageMapFromDefinition(f.CrClient, storageMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForStorageMapReadyWithTimeout(f.CrClient, namespace, test_storage_map_name, 10*time.Second) Expect(err).ToNot(HaveOccurred()) By("Creating plan") planDenf := utils.NewPlanWithVmId(*provider, namespace, test_plan_name, test_storage_map_name, networkMapName, targetNS.Name, []string{vmData.GetTestVMId()}) err = utils.CreatePlanFromDefinition(f.CrClient, planDenf) Expect(err).ToNot(HaveOccurred()) err, _ = utils.WaitForPlanReadyWithTimeout(f.CrClient, namespace, test_plan_name, 15*time.Second) Expect(err).ToNot(HaveOccurred()) By("Creating migration") migrationDef := utils.NewMigration(provider.Namespace, test_migration_name, test_plan_name) err = utils.CreateMigrationFromDefinition(f.CrClient, migrationDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForMigrationSucceededWithTimeout(f.CrClient, provider.Namespace, test_migration_name, 300*time.Second) Expect(err).ToNot(HaveOccurred()) By("Verifying imported VM exists") vmId := types.UID(vmData.GetTestVMId()) vm, err := utils.GetImportedVm(f.CrClient, targetNS.Name, func(vm cnv.VirtualMachine) bool { return vm.Spec.Template.Spec.Domain.Firmware.UUID == vmId }) Expect(err).ToNot(HaveOccurred()) Expect(vm).ToNot(BeNil()) By("Verifying VM is created without the cluster CPU") Expect(vm.Spec.Template.Spec.Domain.CPU.Model).To(BeEmpty()) }) It("[oVirt MTV] should create insecure provider", func() { namespace := f.Namespace.Name By("Load Source VM Details from Ovirt") vmData, err := f.Clients.OvirtClient.LoadSourceDetails() Expect(err).ToNot(HaveOccurred()) By("Reset fakeovirt") pod, err := utils.FindPodByPrefix(f.K8sClient, "konveyor-forklift", "fakeovirt-", "") Expect(err).ToNot(HaveOccurred()) err = utils.DeletePodByName(f.K8sClient, pod.Name, "konveyor-forklift", nil) Expect(err).ToNot(HaveOccurred()) pod, err = utils.FindPodByPrefix(f.K8sClient, "konveyor-forklift", "fakeovirt-", "") Expect(err).ToNot(HaveOccurred()) err = utils.WaitTimeoutForPodReady(f.K8sClient, pod.Name, "konveyor-forklift", 60*time.Second) Expect(err).ToNot(HaveOccurred()) err = f.Clients.OvirtClient.SetupClient(true) Expect(err).ToNot(HaveOccurred()) By("Create Secret from Definition") insecureStr := strconv.FormatBool(f.OvirtClient.Insecure) s, err := utils.CreateSecretFromDefinition(f.K8sClient, utils.NewSecretDefinition( map[string]string{ "createdForProviderType": "ovirt", }, nil, map[string][]byte{ "cacert": []byte(""), "password": []byte(f.OvirtClient.Password), "user": []byte(f.OvirtClient.Username), "url": []byte(f.OvirtClient.OvirtURL), "insecureSkipVerify": []byte(insecureStr), }, namespace, "provider-insecure-test-secret")) Expect(err).ToNot(HaveOccurred()) targetNS, err := f.CreateNamespace("default-insecure", map[string]string{}) Expect(err).ToNot(HaveOccurred()) By("Create target Openshift provider") targetPr := utils.NewProvider(utils.TargetProviderName, forkliftv1.OpenShift, namespace, map[string]string{}, map[string]string{}, "", nil) err = utils.CreateProviderFromDefinition(f.CrClient, targetPr) Expect(err).ToNot(HaveOccurred()) _, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, utils.TargetProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create oVirt provider") pr := utils.NewProvider(ovirtInsecureProviderName, forkliftv1.OVirt, namespace, map[string]string{}, map[string]string{}, f.OvirtClient.OvirtURL, s) err = utils.CreateProviderFromDefinition(f.CrClient, pr) Expect(err).ToNot(HaveOccurred()) _, err = utils.WaitForProviderReadyWithTimeout(f.CrClient, namespace, ovirtInsecureProviderName, 30*time.Second) Expect(err).ToNot(HaveOccurred()) provider, err := utils.GetProvider(f.CrClient, ovirtInsecureProviderName, namespace) Expect(err).ToNot(HaveOccurred()) By("Create Network Map") networkMapDef := utils.NewNetworkMap(namespace, *provider, test_network_map_name_insecure, vmData.GetVMNics()[0]) err = utils.CreateNetworkMapFromDefinition(f.CrClient, networkMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForNetworkMapReadyWithTimeout(f.CrClient, namespace, test_network_map_name_insecure, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Create Storage Map") storageMapDef := utils.NewStorageMap(namespace, *provider, test_storage_map_name_insecure, vmData.GetVMSDs(), ovirtStorageClass) err = utils.CreateStorageMapFromDefinition(f.CrClient, storageMapDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForStorageMapReadyWithTimeout(f.CrClient, namespace, test_storage_map_name_insecure, 30*time.Second) Expect(err).ToNot(HaveOccurred()) By("Creating plan") planDenf := utils.NewPlanWithVmId(*provider, namespace, test_plan_name_insecure, test_storage_map_name_insecure, test_network_map_name_insecure, targetNS.Name, []string{vmData.GetTestVMId()}) // Setting cluster CPU planDenf.Spec.PreserveClusterCPUModel = true err = utils.CreatePlanFromDefinition(f.CrClient, planDenf) Expect(err).ToNot(HaveOccurred()) err, _ = utils.WaitForPlanReadyWithTimeout(f.CrClient, namespace, test_plan_name_insecure, 15*time.Second) Expect(err).ToNot(HaveOccurred()) By("Creating migration") migrationDef := utils.NewMigration(provider.Namespace, test_migration_name_insecure, test_plan_name_insecure) err = utils.CreateMigrationFromDefinition(f.CrClient, migrationDef) Expect(err).ToNot(HaveOccurred()) err = utils.WaitForMigrationSucceededWithTimeout(f.CrClient, provider.Namespace, test_migration_name_insecure, 300*time.Second) Expect(err).ToNot(HaveOccurred()) By("Verifying imported VM exists") vmId := types.UID(vmData.GetTestVMId()) vm, err := utils.GetImportedVm(f.CrClient, targetNS.Name, func(vm cnv.VirtualMachine) bool { return vm.Spec.Template.Spec.Domain.Firmware.UUID == vmId }) Expect(err).ToNot(HaveOccurred()) Expect(vm).ToNot(BeNil()) By("Verifying VM is created with the cluster CPU") Expect(vm.Spec.Template.Spec.Domain.CPU.Model).To(Equal(clusterCpuModel)) }) }) })
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/framework/ova.go
tests/suit/framework/ova.go
package framework import ( "context" "errors" "os" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) // LoadSourceDetails - Load Source VM details from ova func (r *OvaClient) LoadSourceDetails() (vm *OvaVM, err error) { if sc := os.Getenv("STORAGE_CLASS"); sc != "" { r.storageClass = sc } else { r.storageClass = "nfs-csi" } r.vmData.testVmName = "centos44" r.vmData.testNetworkID = "ae1badc8c693926f492a01e2f357d6af321b" r.vmData.testStorageName = "centos44_new-disk1.vmdk" return &r.vmData, nil } func (r *OvaClient) GetNfsServerForOva(k8sClient *kubernetes.Clientset) (string, error) { storageClass, err := k8sClient.StorageV1().StorageClasses().Get(context.TODO(), r.storageClass, metav1.GetOptions{}) if err != nil { return "", err } var server, share string for parm, val := range storageClass.Parameters { if parm == "server" { server = val } if parm == "share" { share = val } } nfsShare := server + ":" + share if nfsShare == "" { return "", errors.New("failed to fetch NFS settings") } r.nfsPath = nfsShare return r.nfsPath, nil } // GetNetworkId - return the network interface for the VM func (r *OvaVM) GetNetworkId() string { return r.testNetworkID } // GetStorageName - return storage domain IDs func (r *OvaVM) GetStorageName() string { return r.testStorageName } // GetVmName - return the test VM name func (r *OvaVM) GetVmName() string { return r.testVmName } type OvaClient struct { vmData OvaVM CustomEnv bool nfsPath string storageClass string } type OvaVM struct { testVmName string testNetworkID string testStorageName string }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/framework/framework.go
tests/suit/framework/framework.go
package framework import ( "bytes" "context" "encoding/json" "fmt" "os" "os/exec" "path/filepath" "sort" "strconv" "time" "github.com/kubev2v/forklift/pkg/apis" "k8s.io/klog/v2" net "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/onsi/ginkgo" "github.com/onsi/gomega" authenticationv1 "k8s.io/api/authentication/v1" v1 "k8s.io/api/core/v1" storagev1 "k8s.io/api/storage/v1" extclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" apierrs "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" cnv "kubevirt.io/api/core/v1" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) const ( nsCreateTime = 60 * time.Second nsDeleteTime = 5 * time.Minute //NsPrefixLabel provides a prefix label to identify the test namespace NsPrefixLabel = "forklift-e2e" timeout = time.Second * 90 pollingInterval = time.Second ) // run-time flags var ( ClientsInstance = &Clients{} reporter = NewKubernetesReporter() ) // Config provides some basic test config options type Config struct { // SkipNamespaceCreation sets whether to skip creating a namespace. Use this ONLY for tests that do not require // a namespace at all, like basic sanity or other global tests. SkipNamespaceCreation bool } // Clients is the struct containing the client-go kubernetes clients type Clients struct { KubectlPath string OcPath string ForkliftInstallNs string KubeConfig string KubeURL string GoCLIPath string DockerPrefix string DockerTag string AutoDeleteNs bool // k8sClient provides our k8s client pointer K8sClient *kubernetes.Clientset // CrClient is a controller runtime client CrClient crclient.Client // DynamicClient performs generic operations on arbitrary k8s API objects. DynamicClient dynamic.Interface RestConfig *rest.Config OvirtClient OvirtClient OpenStackClient OpenStackClient OvaClient OvaClient } // K8s returns Kubernetes Clientset func (c *Clients) K8s() *kubernetes.Clientset { return c.K8sClient } // Framework supports common operations used by functional/e2e tests. It holds the k8s, // a generated unique namespace, run-time flags, and more fields will be added over time as forklift e2e // evolves. Global BeforeEach and AfterEach are called in the Framework constructor. type Framework struct { Config // NsPrefix is a prefix for generated namespace NsPrefix string // Namespace provides a namespace for each test generated/unique ns per test Namespace *v1.Namespace // Namespace2 provides an additional generated/unique secondary ns for testing across namespaces (eg. clone tests) namespacesToDelete []*v1.Namespace // ControllerPod provides a pointer to our test controller pod ControllerPod *v1.Pod *Clients reporter *KubernetesReporter } // NewFramework calls NewFramework and handles errors by calling Fail. Config is optional, but // if passed there can only be one. // To understand the order in which things are run, read http://onsi.github.io/ginkgo/#understanding-ginkgos-lifecycle // flag parsing happens AFTER ginkgo has constructed the entire testing tree. So anything that uses information from flags // cannot work when called during test tree construction. func NewFramework(prefix string, config ...Config) *Framework { cfg := Config{} if len(config) > 0 { cfg = config[0] } f := &Framework{ Config: cfg, NsPrefix: prefix, Clients: ClientsInstance, reporter: reporter, } ginkgo.BeforeEach(f.BeforeEach) ginkgo.AfterEach(f.AfterEach) return f } // BeforeEach provides a set of operations to run before each test func (f *Framework) BeforeEach() { if !f.SkipNamespaceCreation { // generate unique primary ns (ns2 not created here) ginkgo.By(fmt.Sprintf("Building a %q namespace api object", f.NsPrefix)) ns, err := f.CreateNamespace(f.NsPrefix, map[string]string{ NsPrefixLabel: f.NsPrefix, }) gomega.Expect(err).NotTo(gomega.HaveOccurred()) f.Namespace = ns if f.Clients.AutoDeleteNs { f.AddNamespaceToDelete(ns) } } } // AfterEach provides a set of operations to run after each test func (f *Framework) AfterEach() { // delete the namespace(s) in a defer in case future code added here could generate // an exception. For now there is only a defer. defer func() { for _, ns := range f.namespacesToDelete { defer func() { f.namespacesToDelete = nil }() if ns == nil || len(ns.Name) == 0 { continue } ginkgo.By(fmt.Sprintf("Destroying namespace %q for this suite.", ns.Name)) err := DeleteNS(f.K8sClient, ns.Name) gomega.Expect(err).NotTo(gomega.HaveOccurred()) } }() if ginkgo.CurrentGinkgoTestDescription().Failed { f.reporter.FailureCount++ } } // CreateNamespace instantiates a new namespace object with a unique name and the passed-in label(s). func (f *Framework) CreateNamespace(prefix string, labels map[string]string) (*v1.Namespace, error) { if labels == nil { labels = make(map[string]string) } // pod-security.kubernetes.io/<MODE>: <LEVEL> labels["pod-security.kubernetes.io/enforce"] = "restricted" ns := &v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: fmt.Sprintf("forklift-e2e-tests-%s-", prefix), Namespace: "", Labels: labels, }, Status: v1.NamespaceStatus{}, } var nsObj *v1.Namespace c := f.K8sClient err := wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, nsCreateTime, true, func(context.Context) (bool, error) { var err error nsObj, err = c.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{}) if err == nil || apierrs.IsAlreadyExists(err) { return true, nil // done } klog.Warningf("Unexpected error while creating %q namespace: %v", ns.GenerateName, err) return false, err // keep trying }) if err != nil { return nil, err } fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: Created new namespace %q\n", nsObj.Name) return nsObj, nil } // AddNamespaceToDelete provides a wrapper around the go append function func (f *Framework) AddNamespaceToDelete(ns *v1.Namespace) { f.namespacesToDelete = append(f.namespacesToDelete, ns) } // DeleteNS provides a function to delete the specified namespace from the test cluster func DeleteNS(c *kubernetes.Clientset, ns string) error { // return wait.PollImmediate(2*time.Second, nsDeleteTime, func() (bool, error) { err := c.CoreV1().Namespaces().Delete(context.TODO(), ns, metav1.DeleteOptions{}) if err != nil && !apierrs.IsNotFound(err) { return err } return nil } // GetDynamicClient gets an instance of a dynamic client that performs generic operations on arbitrary k8s API objects. func (c *Clients) GetDynamicClient() (dynamic.Interface, error) { cfg, err := clientcmd.BuildConfigFromFlags(c.KubeURL, c.KubeConfig) if err != nil { return nil, err } dyn, err := dynamic.NewForConfig(cfg) if err != nil { return nil, err } return dyn, nil } // GetExtClient gets an instance of a kubernetes client that includes all the api extensions. func (c *Clients) GetExtClient() (*extclientset.Clientset, error) { cfg, err := clientcmd.BuildConfigFromFlags(c.KubeURL, c.KubeConfig) if err != nil { return nil, err } extClient, err := extclientset.NewForConfig(cfg) if err != nil { return nil, err } return extClient, nil } // GetCrClient returns a controller runtime client func (c *Clients) GetCrClient() (crclient.Client, error) { err := forkliftv1.SchemeBuilder.AddToScheme(scheme.Scheme) if err != nil { return nil, err } err = apis.AddToScheme(scheme.Scheme) if err != nil { return nil, err } err = net.AddToScheme(scheme.Scheme) if err != nil { return nil, err } err = cnv.AddToScheme(scheme.Scheme) if err != nil { return nil, err } var client crclient.Client client, err = crclient.New(c.RestConfig, crclient.Options{Scheme: scheme.Scheme}) if err != nil { return nil, err } return client, nil } // GetOvirtClient instantiates and returns an ovirtClient func (c *Clients) GetOvirtClient() (*OvirtClient, error) { oc := OvirtClient{} return &oc, nil } // GetOpenStackClient instantiates and returns an OpenStackClient func (c *Clients) GetOpenStackClient() (*OpenStackClient, error) { oc := OpenStackClient{} return &oc, nil } // GetOvaClient instantiates and returns an OvaClient func (c *Clients) GetOvaClient() (*OvaClient, error) { oc := OvaClient{} return &oc, nil } // GetRESTConfigForServiceAccount returns a RESTConfig for SA func (f *Framework) GetRESTConfigForServiceAccount(namespace, name string) (*rest.Config, error) { token, err := f.GetTokenForServiceAccount(namespace, name) if err != nil { return nil, err } return &rest.Config{ Host: f.RestConfig.Host, APIPath: f.RestConfig.APIPath, BearerToken: string(token), TLSClientConfig: rest.TLSClientConfig{ Insecure: true, }, }, nil } // GetTokenForServiceAccount returns a token for a given SA func (f *Framework) GetTokenForServiceAccount(namespace, name string) (string, error) { token, err := f.K8sClient.CoreV1().ServiceAccounts(namespace). CreateToken( context.TODO(), name, &authenticationv1.TokenRequest{ Spec: authenticationv1.TokenRequestSpec{}, }, metav1.CreateOptions{}, ) if err != nil { return "", err } fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: Token created for SA: %+v\n", token.Status) return token.Status.Token, nil } // GetKubeClient returns a Kubernetes rest client func (c *Clients) GetKubeClient() (*kubernetes.Clientset, error) { return GetKubeClientFromRESTConfig(c.RestConfig) } // LoadConfig loads our specified kubeconfig func (c *Clients) LoadConfig() (*rest.Config, error) { return clientcmd.BuildConfigFromFlags(c.KubeURL, c.KubeConfig) } // GetKubeClientFromRESTConfig provides a function to get a K8s client using hte REST config func GetKubeClientFromRESTConfig(config *rest.Config) (*kubernetes.Clientset, error) { config.APIPath = "/apis" config.ContentType = runtime.ContentTypeJSON return kubernetes.NewForConfig(config) } // CreateQuotaInNs creates a quota and sets it on the current test namespace. func (f *Framework) CreateQuotaInNs(requestCPU, requestMemory, limitsCPU, limitsMemory int64) error { return f.CreateQuotaInSpecifiedNs(f.Namespace.GetName(), requestCPU, requestMemory, limitsCPU, limitsMemory) } // CreateQuotaInSpecifiedNs creates a quota and sets it on the specified test namespace. func (f *Framework) CreateQuotaInSpecifiedNs(ns string, requestCPU, requestMemory, limitsCPU, limitsMemory int64) error { resourceQuota := &v1.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{ Name: "test-quota", Namespace: ns, }, Spec: v1.ResourceQuotaSpec{ Hard: v1.ResourceList{ v1.ResourceRequestsCPU: *resource.NewQuantity(requestCPU, resource.DecimalSI), v1.ResourceRequestsMemory: *resource.NewQuantity(requestMemory, resource.DecimalSI), v1.ResourceLimitsCPU: *resource.NewQuantity(limitsCPU, resource.DecimalSI), v1.ResourceLimitsMemory: *resource.NewQuantity(limitsMemory, resource.DecimalSI), }, }, } _, err := f.K8sClient.CoreV1().ResourceQuotas(ns).Create(context.TODO(), resourceQuota, metav1.CreateOptions{}) if err != nil { ginkgo.Fail("Unable to set resource quota " + err.Error()) } return wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, nsCreateTime, true, func(context.Context) (bool, error) { quota, err := f.K8sClient.CoreV1().ResourceQuotas(ns).Get(context.TODO(), "test-quota", metav1.GetOptions{}) if err != nil { return false, err } return len(quota.Status.Hard) == 4, nil }) } // UpdateQuotaInNs updates an existing quota in the current test namespace. func (f *Framework) UpdateQuotaInNs(requestCPU, requestMemory, limitsCPU, limitsMemory int64) error { resourceQuota := &v1.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{ Name: "test-quota", Namespace: f.Namespace.GetName(), }, Spec: v1.ResourceQuotaSpec{ Hard: v1.ResourceList{ v1.ResourceRequestsCPU: *resource.NewQuantity(requestCPU, resource.DecimalSI), v1.ResourceRequestsMemory: *resource.NewQuantity(requestMemory, resource.DecimalSI), v1.ResourceLimitsCPU: *resource.NewQuantity(limitsCPU, resource.DecimalSI), v1.ResourceLimitsMemory: *resource.NewQuantity(limitsMemory, resource.DecimalSI), }, }, } _, err := f.K8sClient.CoreV1().ResourceQuotas(f.Namespace.GetName()).Update(context.TODO(), resourceQuota, metav1.UpdateOptions{}) if err != nil { ginkgo.Fail("Unable to set resource quota " + err.Error()) } return err } // CreateStorageQuota creates a quota to limit pvc count and cumulative storage capacity func (f *Framework) CreateStorageQuota(numPVCs, requestStorage int64) error { ns := f.Namespace.GetName() resourceQuota := &v1.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{ Name: "test-storage-quota", Namespace: ns, }, Spec: v1.ResourceQuotaSpec{ Hard: v1.ResourceList{ v1.ResourcePersistentVolumeClaims: *resource.NewQuantity(numPVCs, resource.DecimalSI), v1.ResourceRequestsStorage: *resource.NewQuantity(requestStorage, resource.DecimalSI), }, }, } _, err := f.K8sClient.CoreV1().ResourceQuotas(ns).Create(context.TODO(), resourceQuota, metav1.CreateOptions{}) if err != nil { ginkgo.Fail("Unable to set resource quota " + err.Error()) } return wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, nsCreateTime, true, func(context.Context) (bool, error) { quota, err := f.K8sClient.CoreV1().ResourceQuotas(ns).Get(context.TODO(), "test-storage-quota", metav1.GetOptions{}) if err != nil { fmt.Fprintf(ginkgo.GinkgoWriter, "ERROR: GET ResourceQuota failed once, retrying: %v\n", err.Error()) return false, nil } return len(quota.Status.Hard) == 2, nil }) } // UpdateStorageQuota updates an existing storage quota in the current test namespace. func (f *Framework) UpdateStorageQuota(numPVCs, requestStorage int64) error { resourceQuota := &v1.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{ Name: "test-storage-quota", Namespace: f.Namespace.GetName(), }, Spec: v1.ResourceQuotaSpec{ Hard: v1.ResourceList{ v1.ResourcePersistentVolumeClaims: *resource.NewQuantity(numPVCs, resource.DecimalSI), v1.ResourceRequestsStorage: *resource.NewQuantity(requestStorage, resource.DecimalSI), }, }, } _, err := f.K8sClient.CoreV1().ResourceQuotas(f.Namespace.GetName()).Update(context.TODO(), resourceQuota, metav1.UpdateOptions{}) if err != nil { ginkgo.Fail("Unable to set resource quota " + err.Error()) } return wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, nsCreateTime, true, func(context.Context) (bool, error) { quota, err := f.K8sClient.CoreV1().ResourceQuotas(f.Namespace.GetName()).Get(context.TODO(), "test-storage-quota", metav1.GetOptions{}) if err != nil { fmt.Fprintf(ginkgo.GinkgoWriter, "ERROR: GET ResourceQuota failed once, retrying: %v\n", err.Error()) return false, nil } requestStorageUpdated := resource.NewQuantity(requestStorage, resource.DecimalSI).Cmp(quota.Status.Hard[v1.ResourceRequestsStorage]) numPVCsUpdated := resource.NewQuantity(numPVCs, resource.DecimalSI).Cmp(quota.Status.Hard[v1.ResourcePersistentVolumeClaims]) return requestStorageUpdated+numPVCsUpdated == 0, nil }) } // DeleteStorageQuota an existing storage quota in the current test namespace. func (f *Framework) DeleteStorageQuota() error { return wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, nsCreateTime, true, func(context.Context) (bool, error) { err := f.K8sClient.CoreV1().ResourceQuotas(f.Namespace.GetName()).Delete(context.TODO(), "test-storage-quota", metav1.DeleteOptions{}) if err != nil { if apierrs.IsNotFound(err) { return true, nil } fmt.Fprintf(ginkgo.GinkgoWriter, "ERROR: DELETE ResourceQuota failed once, retrying: %v\n", err.Error()) return false, nil } return false, nil }) } // CreateWFFCVariationOfStorageClass creates a WFFC variation of a storage class func (f *Framework) CreateWFFCVariationOfStorageClass(sc *storagev1.StorageClass) (*storagev1.StorageClass, error) { wffc := storagev1.VolumeBindingWaitForFirstConsumer sc.ObjectMeta = metav1.ObjectMeta{ Name: fmt.Sprintf("%s-temp-wffc", sc.Name), } sc.VolumeBindingMode = &wffc return f.K8sClient.StorageV1().StorageClasses().Create(context.TODO(), sc, metav1.CreateOptions{}) } // ExpectEvent polls and fetches events during a defined period of time func (f *Framework) ExpectEvent(dataVolumeNamespace string) gomega.AsyncAssertion { return gomega.Eventually(func() string { events, err := f.runKubectlCommand("get", "events", "-n", dataVolumeNamespace) if err == nil { fmt.Fprintf(ginkgo.GinkgoWriter, "%s", events) return events } fmt.Fprintf(ginkgo.GinkgoWriter, "ERROR: %s\n", err.Error()) return "" }, timeout, pollingInterval) } // runKubectlCommand ... func (f *Framework) runKubectlCommand(args ...string) (string, error) { var errb bytes.Buffer cmd := f.createKubectlCommand(args...) cmd.Stderr = &errb stdOutBytes, err := cmd.Output() if err != nil { if len(errb.String()) > 0 { return errb.String(), err } } return string(stdOutBytes), nil } // createKubectlCommand returns the Cmd to execute kubectl func (f *Framework) createKubectlCommand(args ...string) *exec.Cmd { kubeconfig := f.KubeConfig path := f.KubectlPath cmd := exec.Command(path, args...) kubeconfEnv := fmt.Sprintf("KUBECONFIG=%s", kubeconfig) cmd.Env = append(os.Environ(), kubeconfEnv) return cmd } func getMaxFailsFromEnv() int { maxFailsEnv := os.Getenv("REPORTER_MAX_FAILS") if maxFailsEnv == "" { fmt.Fprintf(os.Stderr, "defaulting to 10 reported failures\n") return 10 } maxFails, err := strconv.Atoi(maxFailsEnv) if err != nil { // if the variable is set with a non int value fmt.Println("Invalid REPORTER_MAX_FAILS variable, defaulting to 10") return 10 } fmt.Fprintf(os.Stderr, "Number of reported failures[%d]\n", maxFails) return maxFails } // KubernetesReporter is the struct that holds the report info. type KubernetesReporter struct { FailureCount int artifactsDir string maxFails int } // NewKubernetesReporter creates a new instance of the reporter. func NewKubernetesReporter() *KubernetesReporter { return &KubernetesReporter{ FailureCount: 0, artifactsDir: os.Getenv("ARTIFACTS"), maxFails: getMaxFailsFromEnv(), } } // Dump dumps the current state of the cluster. The relevant logs are collected starting // from the since parameter. func (r *KubernetesReporter) Dump(kubeCli *kubernetes.Clientset, since time.Duration) { // If we got not directory, print to stderr if r.artifactsDir == "" { return } fmt.Fprintf(os.Stderr, "Current failure count[%d]\n", r.FailureCount) if r.FailureCount > r.maxFails { return } // Can call this as many times as needed, if the directory exists, nothing happens. if err := os.MkdirAll(r.artifactsDir, 0777); err != nil { fmt.Fprintf(os.Stderr, "failed to create directory: %v\n", err) return } r.logCSIDrivers(kubeCli) r.logEvents(kubeCli, since) r.logNodes(kubeCli) r.logPVCs(kubeCli) r.logPVs(kubeCli) r.logPods(kubeCli) r.logServices(kubeCli) r.logEndpoints(kubeCli) r.logLogs(kubeCli, since) } // Cleanup cleans up the current content of the artifactsDir func (r *KubernetesReporter) Cleanup() { // clean up artifacts from previous run if r.artifactsDir != "" { os.RemoveAll(r.artifactsDir) } } func (r *KubernetesReporter) logPods(kubeCli *kubernetes.Clientset) { f, err := os.OpenFile(filepath.Join(r.artifactsDir, fmt.Sprintf("%d_pods.log", r.FailureCount)), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Fprintf(os.Stderr, "failed to open the file: %v", err) return } defer f.Close() pods, err := kubeCli.CoreV1().Pods(v1.NamespaceAll).List(context.TODO(), metav1.ListOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "failed to fetch pods: %v\n", err) return } j, err := json.MarshalIndent(pods, "", " ") if err != nil { return } fmt.Fprintln(f, string(j)) } func (r *KubernetesReporter) logServices(kubeCli *kubernetes.Clientset) { f, err := os.OpenFile(filepath.Join(r.artifactsDir, fmt.Sprintf("%d_services.log", r.FailureCount)), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Fprintf(os.Stderr, "failed to open the file: %v", err) return } defer f.Close() services, err := kubeCli.CoreV1().Services(v1.NamespaceAll).List(context.TODO(), metav1.ListOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "failed to fetch services: %v\n", err) return } j, err := json.MarshalIndent(services, "", " ") if err != nil { return } fmt.Fprintln(f, string(j)) } func (r *KubernetesReporter) logEndpoints(kubeCli *kubernetes.Clientset) { f, err := os.OpenFile(filepath.Join(r.artifactsDir, fmt.Sprintf("%d_endpoints.log", r.FailureCount)), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Fprintf(os.Stderr, "failed to open the file: %v", err) return } defer f.Close() endpoints, err := kubeCli.CoreV1().Endpoints(v1.NamespaceAll).List(context.TODO(), metav1.ListOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "failed to fetch endpointss: %v\n", err) return } j, err := json.MarshalIndent(endpoints, "", " ") if err != nil { return } fmt.Fprintln(f, string(j)) } func (r *KubernetesReporter) logNodes(kubeCli *kubernetes.Clientset) { f, err := os.OpenFile(filepath.Join(r.artifactsDir, fmt.Sprintf("%d_nodes.log", r.FailureCount)), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Fprintf(os.Stderr, "failed to open the file: %v\n", err) return } defer f.Close() nodes, err := kubeCli.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "failed to fetch nodes: %v\n", err) return } j, err := json.MarshalIndent(nodes, "", " ") if err != nil { return } fmt.Fprintln(f, string(j)) } func (r *KubernetesReporter) logPVs(kubeCli *kubernetes.Clientset) { f, err := os.OpenFile(filepath.Join(r.artifactsDir, fmt.Sprintf("%d_pvs.log", r.FailureCount)), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Fprintf(os.Stderr, "failed to open the file: %v\n", err) return } defer f.Close() pvs, err := kubeCli.CoreV1().PersistentVolumes().List(context.TODO(), metav1.ListOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "failed to fetch pvs: %v\n", err) return } j, err := json.MarshalIndent(pvs, "", " ") if err != nil { return } fmt.Fprintln(f, string(j)) } func (r *KubernetesReporter) logPVCs(kubeCli *kubernetes.Clientset) { f, err := os.OpenFile(filepath.Join(r.artifactsDir, fmt.Sprintf("%d_pvcs.log", r.FailureCount)), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Fprintf(os.Stderr, "failed to open the file: %v\n", err) return } defer f.Close() pvcs, err := kubeCli.CoreV1().PersistentVolumeClaims(v1.NamespaceAll).List(context.TODO(), metav1.ListOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "failed to fetch pvcs: %v\n", err) return } j, err := json.MarshalIndent(pvcs, "", " ") if err != nil { return } fmt.Fprintln(f, string(j)) } func (r *KubernetesReporter) logCSIDrivers(kubeCli *kubernetes.Clientset) { f, err := os.OpenFile(filepath.Join(r.artifactsDir, fmt.Sprintf("%d_csidrivers.log", r.FailureCount)), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Fprintf(os.Stderr, "failed to open the file: %v\n", err) return } defer f.Close() csiDrivers, err := kubeCli.StorageV1().CSIDrivers().List(context.TODO(), metav1.ListOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "failed to fetch csidrivers: %v\n", err) return } j, err := json.MarshalIndent(csiDrivers, "", " ") if err != nil { return } fmt.Fprintln(f, string(j)) } func (r *KubernetesReporter) logLogs(kubeCli *kubernetes.Clientset, since time.Duration) { logsdir := filepath.Join(r.artifactsDir, "pods") if err := os.MkdirAll(logsdir, 0777); err != nil { fmt.Fprintf(os.Stderr, "failed to create directory: %v\n", err) return } startTime := time.Now().Add(-since).Add(-5 * time.Second) pods, err := kubeCli.CoreV1().Pods(v1.NamespaceAll).List(context.TODO(), metav1.ListOptions{}) if err != nil { fmt.Fprintf(os.Stderr, "failed to fetch pods: %v\n", err) return } for _, pod := range pods.Items { for _, container := range pod.Spec.Containers { current, err := os.OpenFile(filepath.Join(logsdir, fmt.Sprintf("%d_%s_%s-%s.log", r.FailureCount, pod.Namespace, pod.Name, container.Name)), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Fprintf(os.Stderr, "failed to open the file: %v\n", err) return } defer current.Close() previous, err := os.OpenFile(filepath.Join(logsdir, fmt.Sprintf("%d_%s_%s-%s_previous.log", r.FailureCount, pod.Namespace, pod.Name, container.Name)), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Fprintf(os.Stderr, "failed to open the file: %v\n", err) return } defer previous.Close() logStart := metav1.NewTime(startTime) logs, err := kubeCli.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &v1.PodLogOptions{SinceTime: &logStart, Container: container.Name}).DoRaw(context.TODO()) if err == nil { fmt.Fprintln(current, string(logs)) } logs, err = kubeCli.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &v1.PodLogOptions{SinceTime: &logStart, Container: container.Name, Previous: true}).DoRaw(context.TODO()) if err == nil { fmt.Fprintln(previous, string(logs)) } } } } func (r *KubernetesReporter) logEvents(kubeCli *kubernetes.Clientset, since time.Duration) { f, err := os.OpenFile(filepath.Join(r.artifactsDir, fmt.Sprintf("%d_events.log", r.FailureCount)), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Fprintf(os.Stderr, "failed to open the file: %v\n", err) return } defer f.Close() startTime := time.Now().Add(-since).Add(-5 * time.Second) events, err := kubeCli.CoreV1().Events(v1.NamespaceAll).List(context.TODO(), metav1.ListOptions{}) if err != nil { return } e := events.Items sort.Slice(e, func(i, j int) bool { return e[i].LastTimestamp.After(e[j].LastTimestamp.Time) }) eventsToPrint := v1.EventList{} for _, event := range e { if event.LastTimestamp.Time.After(startTime) { eventsToPrint.Items = append(eventsToPrint.Items, event) } } j, err := json.MarshalIndent(eventsToPrint, "", " ") if err != nil { return } fmt.Fprintln(f, string(j)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/framework/openstack.go
tests/suit/framework/openstack.go
package framework import ( "crypto/x509" "encoding/pem" "fmt" "github.com/kubev2v/forklift/tests/suit/utils" ) func (r *OpenStackClient) SetupClient(vmName string, networkName string, volumeTypeName string) (err error) { r.vmData.testVMName = vmName r.vmData.testNetworkName = networkName r.vmData.testVolumeName = volumeTypeName return nil } // LoadCA - Load CA from openstack func (r *OpenStackClient) LoadCA(f *Framework, namespace string, contName string) (ca string, err error) { pod, err := utils.FindPodByPrefix(f.K8sClient, namespace, contName, fmt.Sprintf("app=%s", contName)) if err != nil { return "", fmt.Errorf("error finding pod for %s - %v", contName, err) } caCert, err := r.getFileContent(f, namespace, pod.Name, contName, "/etc/pki/ca-trust/source/anchors/packstack-ca.pem") if err != nil { return "", fmt.Errorf("error getting CA Certificate - %v", err) } block, _ := pem.Decode([]byte(caCert)) if block == nil { return "", fmt.Errorf("error decoding CA Cert Certificate ") } _, err = x509.ParseCertificate(block.Bytes) if err != nil { return "", fmt.Errorf("error parsing Cert Certificate ") } r.CACertificate = caCert return caCert, nil } // LoadSourceDetails - Load Source VM details from openstack func (r *OpenStackClient) LoadSourceDetails(f *Framework, namespace string, contName string) (vm *OpenStackVM, err error) { pod, err := utils.FindPodByPrefix(f.K8sClient, namespace, contName, fmt.Sprintf("app=%s", contName)) if err != nil { return nil, fmt.Errorf("error finding Pod for %s - %v", contName, err) } vmId, err := r.getIdForEntity(f, namespace, pod.Name, contName, "server", r.vmData.testVMName) if err != nil { return nil, fmt.Errorf("error getting VM ID - %v", err) } networkId, err := r.getIdForEntity(f, namespace, pod.Name, contName, "network", r.vmData.testNetworkName) if err != nil { return nil, fmt.Errorf("error getting Network ID - %v", err) } volumeTypeId, err := r.getIdForEntity(f, namespace, pod.Name, contName, "volume type", r.vmData.testVolumeName) if err != nil { return nil, fmt.Errorf("error getting volume ID - %v", err) } r.vmData.testVMId = vmId r.vmData.networkId = networkId r.vmData.volumeTypeId = volumeTypeId return &r.vmData, nil } // getIdForEntity - get the ID of the osp entity by given name func (r *OpenStackClient) getFileContent(f *Framework, namespace string, podName string, contName string, filename string) (content string, err error) { content, _, err = f.ExecCommandInContainerWithFullOutput(namespace, podName, contName, "/bin/bash", "-c", fmt.Sprintf("cat %s", filename)) return } // getIdForEntity - get the ID of the osp entity by given name func (r *OpenStackClient) getIdForEntity(f *Framework, namespace string, podName string, contName string, entType string, entName string) (id string, err error) { id, _, err = f.ExecCommandInContainerWithFullOutput(namespace, podName, contName, "/bin/bash", "-c", fmt.Sprintf("source /root/keystonerc_admin && openstack %s show %s -c id -f value", entType, entName)) return } // GetNetworkId - return the network interface for the VM func (r *OpenStackVM) GetNetworkId() string { return r.networkId } // GetVolumeId - return storage domain IDs func (r *OpenStackVM) GetVolumeId() string { return r.volumeTypeId } // GetTestVMId - return the test VM ID func (r *OpenStackVM) GetTestVMId() string { return r.testVMId } // OpenStackClient - OpenStack VM Client type OpenStackClient struct { vmData OpenStackVM CustomEnv bool CACertificate string } type OpenStackVM struct { networkId string volumeTypeId string testVMId string testVMName string testNetworkName string testVolumeName string }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/framework/ovirt.go
tests/suit/framework/ovirt.go
package framework import ( "fmt" "os" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref" ovirtsdk "github.com/ovirt/go-ovirt" ) const DefaultStorageClass = "nfs-csi" func (r *OvirtClient) SetupClient(insecure bool) (err error) { r.CustomEnv = false if env := os.Getenv("OVIRT_CUSTOM_ENV"); env == "true" { r.CustomEnv = true } r.storageClass = DefaultStorageClass if sc := os.Getenv("STORAGE_CLASS"); sc != "" { r.storageClass = sc } envVars := []string{"OVIRT_USERNAME", "OVIRT_PASSWORD", "OVIRT_URL"} if !insecure { envVars = append(envVars, "OVIRT_CACERT", "OVIRT_VM_ID") } else { envVars = append(envVars, "OVIRT_INSECURE_VM_ID") } for _, field := range envVars { if env := os.Getenv(field); env == "" { return fmt.Errorf("%s is not set", field) } } if !insecure { cacertFile := os.Getenv("OVIRT_CACERT") fileinput, err := os.ReadFile(cacertFile) if err != nil { return fmt.Errorf("could not read %s", cacertFile) } r.Cacert = fileinput r.Insecure = false r.vmData.testVMId = os.Getenv("OVIRT_VM_ID") } else { r.Insecure = true r.vmData.testVMId = os.Getenv("OVIRT_INSECURE_VM_ID") } r.Username = os.Getenv("OVIRT_USERNAME") r.Password = os.Getenv("OVIRT_PASSWORD") r.OvirtURL = os.Getenv("OVIRT_URL") return } // LoadSourceDetails - Load Source VM details from oVirt func (r *OvirtClient) LoadSourceDetails() (vm *OvirtVM, err error) { // default test values sdomains := []string{"95ef6fee-5773-46a2-9340-a636958a96b8"} nics := []string{"6b6b7239-5ea1-4f08-a76e-be150ab8eb89"} // if a real custom ovirt environment is used. if r.CustomEnv { defer r.Close() err = r.Connect() if err != nil { return nil, fmt.Errorf("error connecting to oVirt engine - %v", err) } // get storage domain from the test VM sdomains, err = r.vmData.getSDFromVM(r.connection, ref.Ref{ID: r.vmData.testVMId}) if err != nil { return nil, fmt.Errorf("error getting storage domains from VM - %v", err) } // get network interface from the test VM nics, err = r.vmData.getNicsFromVM(r.connection, ref.Ref{ID: r.vmData.testVMId}) if err != nil { return nil, fmt.Errorf("error getting network interfaces from VM - %v", err) } } r.vmData.sdPairs = sdomains r.vmData.nicPairs = nics return &r.vmData, nil } // Connect - Connect to the oVirt API. func (r *OvirtClient) Connect() (err error) { builder := ovirtsdk.NewConnectionBuilder(). URL(r.OvirtURL). Username(r.Username). Password(r.Password) if r.Insecure { builder = builder.Insecure(r.Insecure) } else { builder = builder.CACert(r.Cacert) } r.connection, err = builder.Build() if err != nil { return err } return } // Close the connection to the oVirt API. func (r *OvirtClient) Close() { if r.connection != nil { _ = r.connection.Close() r.connection = nil } } // Get the VM by ref. func (r *OvirtVM) getVM(ovirtConn *ovirtsdk.Connection, vmRef ref.Ref) (vmService *ovirtsdk.VmService, err error) { vmService = ovirtConn.SystemService().VmsService().VmService(vmRef.ID) vmResponse, err := vmService.Get().Send() if err != nil { return } _, ok := vmResponse.Vm() if !ok { err = fmt.Errorf( "VM %s source lookup failed", vmRef.String()) } return } // getNicsFromVM - get network interfaces from specific VM func (r *OvirtVM) getNicsFromVM(ovirtConn *ovirtsdk.Connection, vmRef ref.Ref) (nicIds []string, err error) { vmService, err := r.getVM(ovirtConn, vmRef) if err != nil { return nil, fmt.Errorf("failed to get VM - %v", err) } nicsResponse, err := vmService.NicsService().List().Send() nics, ok := nicsResponse.Nics() if !ok { return nil, fmt.Errorf("failed to get nics") } for _, nic := range nics.Slice() { vnicService := ovirtConn.SystemService().VnicProfilesService().ProfileService(nic.MustVnicProfile().MustId()) vnicResponse, err := vnicService.Get().Send() if err != nil { return nil, fmt.Errorf("failed to get vnic service = %v", err) } profile, ok := vnicResponse.Profile() if !ok { return nil, fmt.Errorf("failed to get nic profile") } network, ok := profile.Network() if !ok { return nil, fmt.Errorf("failed to get network") } networkId, ok := network.Id() if !ok { return nil, fmt.Errorf("failed to get network id") } nicIds = append(nicIds, networkId) } return } // getSDFromVM - get storage domains from specific VM func (r *OvirtVM) getSDFromVM(ovirtConn *ovirtsdk.Connection, vmRef ref.Ref) (storageDomains []string, err error) { vmService, err := r.getVM(ovirtConn, vmRef) if err != nil { return nil, fmt.Errorf("failed to get VM - %v", err) } diskAttachementResponse, err := vmService.DiskAttachmentsService().List().Send() if err != nil { return nil, fmt.Errorf("failed to get disk attachment service %v", err) } disks, ok := diskAttachementResponse.Attachments() if !ok { return nil, fmt.Errorf("failed to get disks") } for _, da := range disks.Slice() { disk, ok := da.Disk() if !ok { return nil, fmt.Errorf("failed to get disks") } diskService := ovirtConn.SystemService().DisksService().DiskService(disk.MustId()) diskResponse, err := diskService.Get().Send() if err != nil { return nil, fmt.Errorf("failed to get disks - %v", err) } sds, ok := diskResponse.MustDisk().StorageDomains() if !ok { return nil, fmt.Errorf("failed to get storage domains") } for _, sd := range sds.Slice() { sdId, ok := sd.Id() if !ok { return nil, fmt.Errorf("failed to get storage domain id") } storageDomains = append(storageDomains, sdId) } } return } // GetVMNics - return the network interface for the VM func (r *OvirtVM) GetVMNics() []string { return r.nicPairs } // GetVMSDs - return storage domain IDs func (r *OvirtVM) GetVMSDs() []string { return r.sdPairs } // GetTestVMId - return the test VM ID func (r *OvirtVM) GetTestVMId() string { return r.testVMId } // OvirtClient - oVirt VM Client type OvirtClient struct { connection *ovirtsdk.Connection Cacert []byte Username string OvirtURL string Password string storageClass string vmData OvirtVM CustomEnv bool Insecure bool } type OvirtVM struct { nicPairs []string sdPairs []string testVMId string }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/framework/exec_util.go
tests/suit/framework/exec_util.go
/* Copyright 2016 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 framework import ( "bytes" "context" "fmt" "io" "net/url" "strings" "github.com/onsi/ginkgo" "github.com/onsi/gomega" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/scheme" restclient "k8s.io/client-go/rest" "k8s.io/client-go/tools/remotecommand" ) // ExecOptions passed to ExecWithOptions type ExecOptions struct { Command []string Namespace string PodName string ContainerName string Stdin io.Reader CaptureStdout bool CaptureStderr bool // If false, whitespace in std{err,out} will be removed. PreserveWhitespace bool } // ExecWithOptions executes a command in the specified container, // returning stdout, stderr and error. `options` allowed for // additional parameters to be passed. func (f *Framework) ExecWithOptions(options ExecOptions) (string, string, error) { config := f.RestConfig req := f.K8sClient.CoreV1().RESTClient().Post(). Resource("pods"). Name(options.PodName). Namespace(options.Namespace). SubResource("exec"). Param("container", options.ContainerName) req.VersionedParams(&v1.PodExecOptions{ Container: options.ContainerName, Command: options.Command, Stdin: options.Stdin != nil, Stdout: options.CaptureStdout, Stderr: options.CaptureStderr, TTY: false, }, scheme.ParameterCodec) var stdout, stderr bytes.Buffer err := execute("POST", req.URL(), config, options.Stdin, &stdout, &stderr, false) if options.PreserveWhitespace { return stdout.String(), stderr.String(), err } return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err } // ExecCommandInContainerWithFullOutput executes a command in the // specified container and return stdout, stderr and error func (f *Framework) ExecCommandInContainerWithFullOutput(namespace, podName, containerName string, cmd ...string) (string, string, error) { return f.ExecWithOptions(ExecOptions{ Command: cmd, Namespace: namespace, PodName: podName, ContainerName: containerName, Stdin: nil, CaptureStdout: true, CaptureStderr: true, PreserveWhitespace: false, }) } // ExecCommandInContainer executes a command in the specified container. func (f *Framework) ExecCommandInContainer(namespace, podName, containerName string, cmd ...string) (string, string, error) { stdout, stderr, err := f.ExecCommandInContainerWithFullOutput(namespace, podName, containerName, cmd...) if err != nil { fmt.Fprintf(ginkgo.GinkgoWriter, "[WARN] error executing command %q, error: %s\n", cmd, err.Error()) return "", stderr, err } return stdout, stderr, nil } // ExecShellInContainer provides a function to execute a shell cmd for the specified running container in a pod func (f *Framework) ExecShellInContainer(namespace, podName, containerName string, cmd string) (string, string, error) { stdout, stderr, err := f.ExecCommandInContainer(namespace, podName, containerName, "/bin/sh", "-c", cmd) if err != nil { return "", stderr, err } return stdout, stderr, nil } // ExecCommandInPod provides a function to execute a command on a running pod func (f *Framework) ExecCommandInPod(podName, namespace string, cmd ...string) (string, string, error) { pod, err := f.K8sClient.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{}) gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to get pod") gomega.Expect(pod.Spec.Containers).NotTo(gomega.BeEmpty()) stdout, stderr, err := f.ExecCommandInContainer(namespace, podName, pod.Spec.Containers[0].Name, cmd...) if err != nil { return "", stderr, err } return stdout, stderr, nil } // ExecCommandInPodWithFullOutput provides a function to execute a command in a running pod and to capture its output func (f *Framework) ExecCommandInPodWithFullOutput(namespace, podName string, cmd ...string) (string, string, error) { pod, err := f.K8sClient.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{}) gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to get pod") gomega.Expect(pod.Spec.Containers).NotTo(gomega.BeEmpty()) return f.ExecCommandInContainerWithFullOutput(namespace, podName, pod.Spec.Containers[0].Name, cmd...) } // ExecShellInPod provides a function to execute a shell cmd in the specified pod func (f *Framework) ExecShellInPod(podName, namespace string, cmd string) (string, string, error) { stdout, stderr, err := f.ExecCommandInPod(podName, namespace, "/bin/sh", "-c", cmd) if err != nil { return "", stderr, err } return stdout, stderr, nil } // ExecShellInPodWithFullOutput provides a function to execute a shell cmd in a running pod and to capture its output func (f *Framework) ExecShellInPodWithFullOutput(namespace, podName string, cmd string) (string, string, error) { return f.ExecCommandInPodWithFullOutput(namespace, podName, "/bin/sh", "-c", cmd) } func execute(method string, url *url.URL, config *restclient.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool) error { exec, err := remotecommand.NewSPDYExecutor(config, method, url) if err != nil { return err } return exec.StreamWithContext(context.TODO(), remotecommand.StreamOptions{ Stdin: stdin, Stdout: stdout, Stderr: stderr, Tty: tty, }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/utils/plan.go
tests/suit/utils/plan.go
package utils import ( "context" "fmt" "time" net "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref" corev1 "k8s.io/api/core/v1" apierrs "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) // CreatePlanFromDefinition is used by tests to create a Plan func CreatePlanFromDefinition(cl crclient.Client, def *forkliftv1.Plan) error { err := cl.Create(context.TODO(), def, &crclient.CreateOptions{}) if err == nil || apierrs.IsAlreadyExists(err) { return nil } return err } func NewPlanWithVmName(providerIdentifier forkliftv1.Provider, namespace, planName, storageMap, networkMap string, vmNames []string, targetNameSpace string) *forkliftv1.Plan { planDef := newPlan(providerIdentifier, namespace, planName, storageMap, networkMap, targetNameSpace) planDef.Spec.VMs = []plan.VM{ { Ref: ref.Ref{Name: vmNames[0]}, }, } return planDef } func NewPlanWithVmId(providerIdentifier forkliftv1.Provider, namespace, planName, storageMap, networkMap, targetNameSpace string, vmIds []string) *forkliftv1.Plan { planDef := newPlan(providerIdentifier, namespace, planName, storageMap, networkMap, targetNameSpace) planDef.Spec.VMs = []plan.VM{ { Ref: ref.Ref{ID: vmIds[0]}, }, } return planDef } func newPlan(providerIdentifier forkliftv1.Provider, namespace, planName, storageMap, networkMap, targetNameSpace string) *forkliftv1.Plan { plan := &forkliftv1.Plan{ TypeMeta: v1.TypeMeta{ Kind: "Plan", APIVersion: "forklift.konveyor.io/v1beta1", }, ObjectMeta: v1.ObjectMeta{ Name: planName, Namespace: providerIdentifier.Namespace, }, Spec: forkliftv1.PlanSpec{ Provider: provider.Pair{ Destination: corev1.ObjectReference{ Name: TargetProviderName, Namespace: providerIdentifier.Namespace, }, Source: corev1.ObjectReference{ Name: providerIdentifier.Name, Namespace: providerIdentifier.Namespace, }}, Archived: false, Warm: false, TargetNamespace: targetNameSpace, Map: plan.Map{ Storage: corev1.ObjectReference{ Name: storageMap, Namespace: providerIdentifier.Namespace, }, Network: corev1.ObjectReference{ Name: networkMap, Namespace: providerIdentifier.Namespace, }, }, }, } return plan } func GetPlan(cl crclient.Client, namespace, planName string) (error, *forkliftv1.Plan) { planIdentifier := types.NamespacedName{Namespace: namespace, Name: planName} plan := &forkliftv1.Plan{} err := cl.Get(context.TODO(), planIdentifier, plan) return err, plan } func UpdatePlanWarmMigration(cl crclient.Client, plan *forkliftv1.Plan, isWarmMigration bool) error { plan.Spec.Warm = isWarmMigration return cl.Update(context.TODO(), plan) } func WaitForPlanReadyWithTimeout(cl crclient.Client, namespace, planName string, timeout time.Duration) (error, *forkliftv1.Plan) { planIdentifier := types.NamespacedName{Namespace: namespace, Name: planName} returnedMap := &forkliftv1.Plan{} err := wait.PollUntilContextTimeout(context.TODO(), 3*time.Second, timeout, true, func(context.Context) (bool, error) { err := cl.Get(context.TODO(), planIdentifier, returnedMap) if err != nil || !returnedMap.Status.Conditions.IsReady() { return false, err } return true, nil }) if err != nil { return fmt.Errorf("Plan %s not ready within %v", planName, timeout), returnedMap } return nil, returnedMap } func CreateNetworkAttachmentDefinition(cl crclient.Client, name, namespace string) (error, *net.NetworkAttachmentDefinition) { nad := &net.NetworkAttachmentDefinition{ ObjectMeta: v1.ObjectMeta{ Name: name, Namespace: namespace, }, } err := cl.Create(context.TODO(), nad, &crclient.CreateOptions{}) return err, nad } func DeleteNetworkAttachmentDefinition(cl crclient.Client, name, namespace string) error { nad := &net.NetworkAttachmentDefinition{ ObjectMeta: v1.ObjectMeta{ Name: name, Namespace: namespace, }, } err := cl.Delete(context.TODO(), nad) return err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/utils/pod.go
tests/suit/utils/pod.go
package utils import ( "context" "fmt" "strings" "time" "github.com/onsi/ginkgo" k8sv1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" ) const ( defaultPollInterval = 2 * time.Second defaultPollPeriod = 270 * time.Second defaultPollPeriodFast = 30 * time.Second // PodWaitForTime is the time to wait for Pod operations to complete PodWaitForTime = defaultPollPeriod // PodWaitForTimeFast is the fast time to wait for Pod operations to complete (30 sec) PodWaitForTimeFast = defaultPollPeriodFast // PodWaitIntervalFast is the fast polling interval (250ms) PodWaitIntervalFast = 250 * time.Millisecond podCreateTime = defaultPollPeriod podDeleteTime = defaultPollPeriod //VerifierPodName is the name of the verifier pod. VerifierPodName = "verifier" ) // DeleteVerifierPod deletes the verifier pod func DeleteVerifierPod(clientSet *kubernetes.Clientset, namespace string) error { return DeletePodByName(clientSet, VerifierPodName, namespace, nil) } // CreatePod calls the Kubernetes API to create a Pod func CreatePod(clientSet *kubernetes.Clientset, namespace string, podDef *k8sv1.Pod) (*k8sv1.Pod, error) { err := wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, podCreateTime, true, func(context.Context) (bool, error) { var err error _, err = clientSet.CoreV1().Pods(namespace).Create(context.TODO(), podDef, metav1.CreateOptions{}) if err != nil { return false, err } return true, nil }) return podDef, err } // DeletePodByName deletes the pod based on the passed in name from the passed in Namespace func DeletePodByName(clientSet *kubernetes.Clientset, podName, namespace string, gracePeriod *int64) error { _ = clientSet.CoreV1().Pods(namespace).Delete(context.TODO(), podName, metav1.DeleteOptions{ GracePeriodSeconds: gracePeriod, }) return wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, podDeleteTime, true, func(context.Context) (bool, error) { _, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{}) if k8serrors.IsNotFound(err) { return true, nil } return false, err }) } // DeletePodNoGrace deletes the passed in Pod from the passed in Namespace func DeletePodNoGrace(clientSet *kubernetes.Clientset, pod *k8sv1.Pod, namespace string) error { zero := int64(0) return DeletePodByName(clientSet, pod.Name, namespace, &zero) } // DeletePod deletes the passed in Pod from the passed in Namespace func DeletePod(clientSet *kubernetes.Clientset, pod *k8sv1.Pod, namespace string) error { return DeletePodByName(clientSet, pod.Name, namespace, nil) } // FindPodBySuffix finds the first pod which has the passed in suffix. Returns error if multiple pods with the same suffix are found. func FindPodBySuffix(clientSet *kubernetes.Clientset, namespace, suffix, labelSelector string) (*k8sv1.Pod, error) { return findPodByCompFunc(clientSet, namespace, suffix, labelSelector, strings.HasSuffix) } // FindPodByPrefix finds the first pod which has the passed in prefix. Returns error if multiple pods with the same prefix are found. func FindPodByPrefix(clientSet *kubernetes.Clientset, namespace, prefix, labelSelector string) (*k8sv1.Pod, error) { return findPodByCompFunc(clientSet, namespace, prefix, labelSelector, strings.HasPrefix) } // FindPodBySuffixOnce finds once (no polling) the first pod which has the passed in suffix. Returns error if multiple pods with the same suffix are found. func FindPodBySuffixOnce(clientSet *kubernetes.Clientset, namespace, suffix, labelSelector string) (*k8sv1.Pod, error) { return findPodByCompFuncOnce(clientSet, namespace, suffix, labelSelector, strings.HasSuffix) } // FindPodByPrefixOnce finds once (no polling) the first pod which has the passed in prefix. Returns error if multiple pods with the same prefix are found. func FindPodByPrefixOnce(clientSet *kubernetes.Clientset, namespace, prefix, labelSelector string) (*k8sv1.Pod, error) { return findPodByCompFuncOnce(clientSet, namespace, prefix, labelSelector, strings.HasPrefix) } func findPodByCompFunc(clientSet *kubernetes.Clientset, namespace, prefix, labelSelector string, compFunc func(string, string) bool) (*k8sv1.Pod, error) { var result *k8sv1.Pod var err error err = wait.PollUntilContextCancel(context.TODO(), 2*time.Second, true, func(ctx context.Context) (bool, error) { result, err = findPodByCompFuncOnce(clientSet, namespace, prefix, labelSelector, compFunc) if result != nil { return true, err } // If no result yet, continue polling even if there is an error return false, nil }) return result, err } func findPodByCompFuncOnce(clientSet *kubernetes.Clientset, namespace, prefix, labelSelector string, compFunc func(string, string) bool) (*k8sv1.Pod, error) { var result *k8sv1.Pod podList, err := clientSet.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{ LabelSelector: labelSelector, }) if err != nil { return nil, err } for _, pod := range podList.Items { if compFunc(pod.Name, prefix) { if result == nil { result = pod.DeepCopy() } else { fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: First pod name %s in namespace %s\n", result.Name, result.Namespace) fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: Second pod name %s in namespace %s\n", pod.Name, pod.Namespace) return result, fmt.Errorf("multiple pods starting with prefix %q in namespace %q", prefix, namespace) } } } if result == nil { return nil, k8serrors.NewNotFound(k8sv1.Resource("pod"), prefix) } return result, nil } // WaitTimeoutForPodReady waits for the given pod to be created and ready func WaitTimeoutForPodReady(clientSet *kubernetes.Clientset, podName, namespace string, timeout time.Duration) error { return WaitTimeoutForPodCondition(clientSet, podName, namespace, k8sv1.PodReady, 2*time.Second, timeout) } // WaitTimeoutForPodReadyPollPeriod waits for the given pod to be created and ready using the passed in poll period func WaitTimeoutForPodReadyPollPeriod(clientSet *kubernetes.Clientset, podName, namespace string, pollperiod, timeout time.Duration) error { return WaitTimeoutForPodCondition(clientSet, podName, namespace, k8sv1.PodReady, pollperiod, timeout) } // WaitTimeoutForPodSucceeded waits for pod to succeed func WaitTimeoutForPodSucceeded(clientSet *kubernetes.Clientset, podName, namespace string, timeout time.Duration) error { return WaitTimeoutForPodStatus(clientSet, podName, namespace, k8sv1.PodSucceeded, timeout) } // WaitTimeoutForPodFailed waits for pod to fail func WaitTimeoutForPodFailed(clientSet *kubernetes.Clientset, podName, namespace string, timeout time.Duration) error { return WaitTimeoutForPodStatus(clientSet, podName, namespace, k8sv1.PodFailed, timeout) } // WaitTimeoutForPodStatus waits for the given pod to be created and have a expected status func WaitTimeoutForPodStatus(clientSet *kubernetes.Clientset, podName, namespace string, status k8sv1.PodPhase, timeout time.Duration) error { return wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, timeout, true, podStatus(clientSet, podName, namespace, status)) } // WaitTimeoutForPodCondition waits for the given pod to be created and have an expected condition func WaitTimeoutForPodCondition(clientSet *kubernetes.Clientset, podName, namespace string, conditionType k8sv1.PodConditionType, pollperiod, timeout time.Duration) error { return wait.PollUntilContextTimeout(context.TODO(), pollperiod, timeout, true, podCondition(clientSet, podName, namespace, conditionType)) } func podStatus(clientSet *kubernetes.Clientset, podName, namespace string, status k8sv1.PodPhase) wait.ConditionWithContextFunc { return func(context.Context) (bool, error) { pod, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{}) if err != nil { if k8serrors.IsNotFound(err) { return false, nil } return false, err } fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: Checking POD %s phase: %s\n", podName, string(pod.Status.Phase)) switch pod.Status.Phase { case status: return true, nil } return false, nil } } func podCondition(clientSet *kubernetes.Clientset, podName, namespace string, conditionType k8sv1.PodConditionType) wait.ConditionWithContextFunc { return func(context.Context) (bool, error) { pod, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{}) if err != nil { if k8serrors.IsNotFound(err) { return false, nil } return false, err } for _, cond := range pod.Status.Conditions { if cond.Type == conditionType { fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: Checking POD %s condition: %s=%s\n", podName, string(cond.Type), string(cond.Status)) if cond.Status == k8sv1.ConditionTrue { return true, nil } } } return false, nil } } // PodGetNode returns the node on which a given pod is executing func PodGetNode(clientSet *kubernetes.Clientset, podName, namespace string) (string, error) { pod, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{}) if err != nil { return "", err } return pod.Spec.NodeName, nil } // WaitPodDeleted waits fo a pod to no longer exist // returns whether the pod is deleted along with any error func WaitPodDeleted(clientSet *kubernetes.Clientset, podName, namespace string, timeout time.Duration) (bool, error) { var result bool err := wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, timeout, true, func(context.Context) (bool, error) { _, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{}) if err != nil { if k8serrors.IsNotFound(err) { result = true return true, nil } return false, err } return false, nil }) return result, err } // IsExpectedNode waits to check if the specified pod is schedule on the specified node func IsExpectedNode(clientSet *kubernetes.Clientset, nodeName, podName, namespace string, timeout time.Duration) error { return wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, timeout, true, isExpectedNode(clientSet, nodeName, podName, namespace)) } // returns true is the specified pod running on the specified nodeName. Otherwise returns false func isExpectedNode(clientSet *kubernetes.Clientset, nodeName, podName, namespace string) wait.ConditionWithContextFunc { return func(context.Context) (bool, error) { pod, err := clientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{}) if err != nil { if k8serrors.IsNotFound(err) { return false, nil } return false, err } fmt.Fprintf(ginkgo.GinkgoWriter, "INFO: Checking Node name: %s\n", string(pod.Spec.NodeName)) if pod.Spec.NodeName == nodeName { return true, nil } return false, nil } } // GetSchedulableNode return a schedulable node from a nodes list func GetSchedulableNode(nodes *k8sv1.NodeList) *string { for _, node := range nodes.Items { if node.Spec.Taints == nil { return &node.Name } schedulableNode := true for _, taint := range node.Spec.Taints { if taint.Effect == "NoSchedule" { schedulableNode = false break } } if schedulableNode { return &node.Name } } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/utils/networkmap.go
tests/suit/utils/networkmap.go
package utils import ( "context" "fmt" "time" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref" corev1 "k8s.io/api/core/v1" apierrs "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) // CreateNetworkMapFromDefinition is used by tests to create a NetworkMap func CreateNetworkMapFromDefinition(cl crclient.Client, def *forkliftv1.NetworkMap) error { err := cl.Create(context.TODO(), def, &crclient.CreateOptions{}) if err == nil || apierrs.IsAlreadyExists(err) { return nil } return err } func NewNetworkMap(namespace string, providerIdentifier forkliftv1.Provider, networkMapName string, sourceNicID string) *forkliftv1.NetworkMap { // nicPairs set with the default settings for kind CI. nicPairs := []forkliftv1.NetworkPair{ { Source: ref.Ref{ID: sourceNicID}, Destination: forkliftv1.DestinationNetwork{ Type: "pod", }, }, } networkMap := &forkliftv1.NetworkMap{ TypeMeta: v1.TypeMeta{ Kind: "NetworkMap", APIVersion: "forklift.konveyor.io/v1beta1", }, ObjectMeta: v1.ObjectMeta{ Name: networkMapName, Namespace: providerIdentifier.Namespace, }, Spec: forkliftv1.NetworkMapSpec{ Map: nicPairs, Provider: provider.Pair{ Destination: corev1.ObjectReference{ Name: "host", Namespace: forklift_namespace, }, Source: corev1.ObjectReference{ Name: providerIdentifier.Name, Namespace: providerIdentifier.Namespace, }}, }, } return networkMap } func WaitForNetworkMapReadyWithTimeout(cl crclient.Client, namespace, networkMapName string, timeout time.Duration) error { networkMapIdentifier := types.NamespacedName{Namespace: namespace, Name: networkMapName} returnedNetworkMap := &forkliftv1.NetworkMap{} err := wait.PollUntilContextTimeout(context.TODO(), 3*time.Second, timeout, true, func(context.Context) (bool, error) { err := cl.Get(context.TODO(), networkMapIdentifier, returnedNetworkMap) if err != nil || !returnedNetworkMap.Status.Conditions.IsReady() { return false, err } return true, nil }) if err != nil { return fmt.Errorf("NetworkMap %s not ready within %v", networkMapName, timeout) } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/utils/secrets.go
tests/suit/utils/secrets.go
package utils import ( "context" "github.com/pkg/errors" v1 "k8s.io/api/core/v1" apierrs "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" ) const ( secretPollPeriod = defaultPollPeriod secretPollInterval = defaultPollInterval ) // NewSecretDefinition provides a function to initialize a Secret data type with the provided options func NewSecretDefinition(labels, stringData map[string]string, data map[string][]byte, ns, prefix string) *v1.Secret { return &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ GenerateName: prefix, Namespace: ns, Labels: labels, }, StringData: stringData, Data: data, } } // CreateSecretFromDefinition creates and returns a pointer ot a v1.Secret using a provided v1.Secret func CreateSecretFromDefinition(c *kubernetes.Clientset, definition *v1.Secret) (secret *v1.Secret, err error) { secret, err = c.CoreV1().Secrets(definition.Namespace).Create(context.TODO(), definition, metav1.CreateOptions{}) if err != nil { klog.Error(errors.Wrapf(err, "Encountered create error for secret \"%s/%s\"", definition.Namespace, definition.GenerateName)) } return } // DeleteSecret ... func DeleteSecret(clientSet *kubernetes.Clientset, namespace string, secret v1.Secret) error { e := wait.PollUntilContextTimeout(context.TODO(), secretPollInterval, secretPollPeriod, true, func(context.Context) (bool, error) { err := clientSet.CoreV1().Secrets(namespace).Delete(context.TODO(), secret.GetName(), metav1.DeleteOptions{}) if err == nil || apierrs.IsNotFound(err) { return true, nil } return false, nil //keep polling }) return e } func GetSecret(clientSet *kubernetes.Clientset, namespace, name string) (*v1.Secret, error) { return clientSet.CoreV1().Secrets(namespace).Get(context.TODO(), name, metav1.GetOptions{}) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/utils/storagemap.go
tests/suit/utils/storagemap.go
package utils import ( "context" "fmt" "time" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref" corev1 "k8s.io/api/core/v1" apierrs "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) // CreateStorageMapFromDefinition is used by tests to create a StorageMap func CreateStorageMapFromDefinition(cl crclient.Client, def *forkliftv1.StorageMap) error { err := cl.Create(context.TODO(), def, &crclient.CreateOptions{}) if err == nil || apierrs.IsAlreadyExists(err) { return nil } return err } func NewStorageMap(namespace string, providerIdentifier forkliftv1.Provider, storageMapName string, storageIDs []string, storageClass string) *forkliftv1.StorageMap { sdPairs := []forkliftv1.StoragePair{} for _, sd := range storageIDs { pair := forkliftv1.StoragePair{ Destination: forkliftv1.DestinationStorage{ StorageClass: storageClass, }, } switch providerIdentifier.Type() { case forkliftv1.Ova: pair.Source = ref.Ref{Name: sd} default: pair.Source = ref.Ref{ID: sd} } sdPairs = append(sdPairs, pair) } storageMap := &forkliftv1.StorageMap{ TypeMeta: v1.TypeMeta{ Kind: "StorageMap", APIVersion: "forklift.konveyor.io/v1beta1", }, ObjectMeta: v1.ObjectMeta{ Name: storageMapName, Namespace: providerIdentifier.Namespace, }, Spec: forkliftv1.StorageMapSpec{ Map: sdPairs, Provider: provider.Pair{ Destination: corev1.ObjectReference{ Name: "host", Namespace: forklift_namespace, }, Source: corev1.ObjectReference{ Name: providerIdentifier.Name, Namespace: providerIdentifier.Namespace, }}, }, } return storageMap } func WaitForStorageMapReadyWithTimeout(cl crclient.Client, namespace string, storageMapName string, timeout time.Duration) error { storageMapIdentifier := types.NamespacedName{Namespace: namespace, Name: storageMapName} returnedStorageMap := &forkliftv1.StorageMap{} err := wait.PollUntilContextTimeout(context.TODO(), 3*time.Second, timeout, true, func(context.Context) (bool, error) { err := cl.Get(context.TODO(), storageMapIdentifier, returnedStorageMap) if err != nil || !returnedStorageMap.Status.Conditions.IsReady() { return false, err } return true, nil }) if err != nil { //return fmt.Errorf("StorageMap %s not ready within %v", storageMapName, timeout) conditions := returnedStorageMap.Status.Conditions.List return fmt.Errorf("StorageMap %s not ready within %v - condition: %v", storageMapName, timeout, conditions[len(conditions)-1].Message) } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/utils/http.go
tests/suit/utils/http.go
package utils import ( "crypto/tls" "crypto/x509" "fmt" "net" "net/http" "time" liberr "github.com/kubev2v/forklift/pkg/lib/error" ) func TestHttpsCA(url string, caCert string, isInsecure bool) (err error) { cacert := []byte(caCert) roots := x509.NewCertPool() ok := roots.AppendCertsFromPEM(cacert) if !ok { fmt.Println("the CA certificate is malformed or was not provided, falling back to system CA cert pool") roots, err = x509.SystemCertPool() if err != nil { err = liberr.New("failed to configure the system's cert pool") return } } TLSClientConfig := &tls.Config{RootCAs: roots} HTTPClient := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 10 * time.Second, KeepAlive: 10 * time.Second, }).DialContext, MaxIdleConns: 10, IdleConnTimeout: 10 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, TLSClientConfig: TLSClientConfig, }, } resp, err := HTTPClient.Get(url) if err != nil { return err } defer resp.Body.Close() return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/utils/provider.go
tests/suit/utils/provider.go
package utils import ( "context" "fmt" "time" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" "github.com/onsi/ginkgo" corev1 "k8s.io/api/core/v1" apierrs "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) func NewProvider(providerName string, providerType forkliftv1.ProviderType, namespace string, annotations, providerSetting map[string]string, url string, secret *corev1.Secret) forkliftv1.Provider { // nicPairs set with the default settings for kind CI. providerMeta := v1.ObjectMeta{ Namespace: namespace, Name: providerName, Annotations: annotations, } var secretRef corev1.ObjectReference if secret != nil { secretRef = corev1.ObjectReference{ Name: secret.Name, Namespace: namespace, } } p := forkliftv1.Provider{ TypeMeta: v1.TypeMeta{ Kind: "Provider", APIVersion: "forklift.konveyor.io/v1beta1", }, ObjectMeta: providerMeta, Spec: forkliftv1.ProviderSpec{ Type: &providerType, URL: url, Settings: providerSetting, Secret: secretRef, }, } return p } func WaitForProviderReadyWithTimeout(cl crclient.Client, namespace string, providerName string, timeout time.Duration) (*forkliftv1.Provider, error) { providerIdentifier := types.NamespacedName{Namespace: namespace, Name: providerName} returnedProvider := &forkliftv1.Provider{} err := wait.PollUntilContextTimeout(context.TODO(), 3*time.Second, timeout, true, func(context.Context) (bool, error) { err := cl.Get(context.TODO(), providerIdentifier, returnedProvider) if err != nil || !returnedProvider.Status.Conditions.IsReady() { return false, err } return true, nil }) if err != nil { conditions := returnedProvider.Status.Conditions.List msg := "<no conditions>" if len(conditions) > 0 { msg = conditions[len(conditions)-1].Message } return nil, fmt.Errorf("provider %s not ready within %v - Phase/condition: %v/%v", providerName, timeout, returnedProvider.Status.Phase, msg) } return returnedProvider, nil } // CreateProviderFromDefinition is used by tests to create a Provider func CreateProviderFromDefinition(cl crclient.Client, def forkliftv1.Provider) error { err := cl.Create(context.TODO(), &def, &crclient.CreateOptions{}) if err == nil || apierrs.IsAlreadyExists(err) { return nil } return err } // GetProvider returns provider object func GetProvider(cl crclient.Client, providerName string, namespace string) (*forkliftv1.Provider, error) { returnedProvider := &forkliftv1.Provider{} providerObj := v1.ObjectMeta{ Namespace: namespace, Name: providerName, } providerIdentifier := types.NamespacedName{Namespace: providerObj.Namespace, Name: providerObj.Name} fmt.Fprintf(ginkgo.GinkgoWriter, "DEBUG: %s", providerObj.Namespace) err := cl.Get(context.TODO(), providerIdentifier, returnedProvider) if err != nil { return nil, err } return returnedProvider, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/utils/migration.go
tests/suit/utils/migration.go
package utils import ( "context" "errors" "fmt" "time" forkliftv1 "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1" corev1 "k8s.io/api/core/v1" apierrs "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" cnv "kubevirt.io/api/core/v1" crclient "sigs.k8s.io/controller-runtime/pkg/client" ) // CreateMigrationFromDefinition is used by tests to create a Plan func CreateMigrationFromDefinition(cl crclient.Client, def *forkliftv1.Migration) error { err := cl.Create(context.TODO(), def, &crclient.CreateOptions{}) if err == nil || apierrs.IsAlreadyExists(err) { return nil } return err } func NewMigration(namespace string, migrationName string, planName string) *forkliftv1.Migration { migration := &forkliftv1.Migration{ TypeMeta: v1.TypeMeta{ Kind: "Migration", APIVersion: "forklift.konveyor.io/v1beta1", }, ObjectMeta: v1.ObjectMeta{ Name: migrationName, Namespace: namespace, }, Spec: forkliftv1.MigrationSpec{ Plan: corev1.ObjectReference{ Name: planName, Namespace: namespace, }, }, } return migration } func WaitForMigrationSucceededWithTimeout(cl crclient.Client, namespace string, migrationName string, timeout time.Duration) error { migrationIdentifier := types.NamespacedName{Namespace: namespace, Name: migrationName} returnedMap := &forkliftv1.Migration{} err := wait.PollUntilContextTimeout(context.TODO(), 3*time.Second, timeout, true, func(context.Context) (bool, error) { err := cl.Get(context.TODO(), migrationIdentifier, returnedMap) //terminate the retry if migration failed if condition := returnedMap.Status.Conditions.FindCondition("Failed"); condition != nil { return true, fmt.Errorf("migration failed %v", returnedMap.Status.VMs[0].Error.Reasons) } if err != nil || returnedMap.Status.Conditions.FindCondition("Succeeded") == nil { // find out the reason why migration failed if len(returnedMap.Status.VMs) > 0 && returnedMap.Status.VMs[0].Error != nil { err = fmt.Errorf("error: %s", returnedMap.Status.VMs[0].Error.Reasons) } return false, err } return true, nil }) if err != nil { return fmt.Errorf("migrtation %s not ready within %v, error: %w", migrationName, timeout, err) } return nil } func GetImportedVm(cl crclient.Client, namespace string, isImportedVm func(cnv.VirtualMachine) bool) (*cnv.VirtualMachine, error) { vms := &cnv.VirtualMachineList{} if err := cl.List(context.TODO(), vms, &crclient.ListOptions{Namespace: namespace}); err != nil { return nil, err } for _, vm := range vms.Items { if isImportedVm(vm) { return &vm, nil } } return nil, errors.New("no imported VM found") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/tests/suit/utils/common.go
tests/suit/utils/common.go
package utils import ( "context" "fmt" "os" "os/exec" "github.com/onsi/ginkgo" storagev1 "k8s.io/api/storage/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) // fedora const UpdateTrustCMD = "sudo update-ca-trust" const SystemCAPath = "/etc/pki/ca-trust/source/anchors/packstack.crt" // Ubuntu //const UpdateTrustCMD = "sudo update-ca-certificates" //const SystemCAPath = "/usr/local/share/ca-certificates/packstack.crt" var ( // DefaultStorageClass the default storage class used in tests DefaultStorageClass *storagev1.StorageClass forklift_namespace = "konveyor-forklift" TargetProviderName = "host" ) // ClientsIface is the clients interface type ClientsIface interface { K8s() *kubernetes.Clientset } // GetDefaultStorageClass return the storage class which is marked as default in the cluster func GetDefaultStorageClass(client *kubernetes.Clientset) *storagev1.StorageClass { storageclasses, err := client.StorageV1().StorageClasses().List(context.TODO(), metav1.ListOptions{}) if err != nil { ginkgo.Fail("Unable to list storage classes") return nil } for _, storageClass := range storageclasses.Items { if storageClass.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" { return &storageClass } } ginkgo.Fail("Unable to find default storage classes") return nil } // CacheTestsData fetch and cache data required for tests func CacheTestsData(client *kubernetes.Clientset, cdiNs string) { if DefaultStorageClass == nil { DefaultStorageClass = GetDefaultStorageClass(client) } } func RemoveLocalCA() error { cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("sudo rm -rf %s && %s", SystemCAPath, UpdateTrustCMD)) if err := cmd.Run(); err != nil { return err } return nil } func UpdateLocalCA(caCert string) error { file, err := os.CreateTemp("/tmp", "prefix") if err != nil { return err } // write the CA into the Temp file _, err = file.WriteString(caCert) if err != nil { return err } defer os.Remove(file.Name()) fmt.Println(file.Name()) // ginkgo.Fail(fmt.Sprintf("Unable to get filenams: %s", file.Name())) cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("sudo cp %s %s && %s", file.Name(), SystemCAPath, UpdateTrustCMD)) if err := cmd.Run(); err != nil { return err } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/box.go
Bcore/windows/resources/sing-box-main/box.go
package box import ( "context" "fmt" "io" "os" "runtime/debug" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/taskmonitor" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/experimental" "github.com/sagernet/sing-box/experimental/cachefile" "github.com/sagernet/sing-box/experimental/libbox/platform" "github.com/sagernet/sing-box/inbound" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/outbound" "github.com/sagernet/sing-box/route" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" "github.com/sagernet/sing/service" "github.com/sagernet/sing/service/pause" ) var _ adapter.Service = (*Box)(nil) type Box struct { createdAt time.Time router adapter.Router inbounds []adapter.Inbound outbounds []adapter.Outbound logFactory log.Factory logger log.ContextLogger preServices1 map[string]adapter.Service preServices2 map[string]adapter.Service postServices map[string]adapter.Service done chan struct{} } type Options struct { option.Options Context context.Context PlatformInterface platform.Interface PlatformLogWriter log.PlatformWriter } func New(options Options) (*Box, error) { createdAt := time.Now() ctx := options.Context if ctx == nil { ctx = context.Background() } ctx = service.ContextWithDefaultRegistry(ctx) ctx = pause.WithDefaultManager(ctx) experimentalOptions := common.PtrValueOrDefault(options.Experimental) applyDebugOptions(common.PtrValueOrDefault(experimentalOptions.Debug)) var needCacheFile bool var needClashAPI bool var needV2RayAPI bool if experimentalOptions.CacheFile != nil && experimentalOptions.CacheFile.Enabled || options.PlatformLogWriter != nil { needCacheFile = true } if experimentalOptions.ClashAPI != nil || options.PlatformLogWriter != nil { needClashAPI = true } if experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != "" { needV2RayAPI = true } var defaultLogWriter io.Writer if options.PlatformInterface != nil { defaultLogWriter = io.Discard } logFactory, err := log.New(log.Options{ Context: ctx, Options: common.PtrValueOrDefault(options.Log), Observable: needClashAPI, DefaultWriter: defaultLogWriter, BaseTime: createdAt, PlatformWriter: options.PlatformLogWriter, }) if err != nil { return nil, E.Cause(err, "create log factory") } router, err := route.NewRouter( ctx, logFactory, common.PtrValueOrDefault(options.Route), common.PtrValueOrDefault(options.DNS), common.PtrValueOrDefault(options.NTP), options.Inbounds, options.PlatformInterface, ) if err != nil { return nil, E.Cause(err, "parse route options") } inbounds := make([]adapter.Inbound, 0, len(options.Inbounds)) outbounds := make([]adapter.Outbound, 0, len(options.Outbounds)) for i, inboundOptions := range options.Inbounds { var in adapter.Inbound var tag string if inboundOptions.Tag != "" { tag = inboundOptions.Tag } else { tag = F.ToString(i) } in, err = inbound.New( ctx, router, logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")), tag, inboundOptions, options.PlatformInterface, ) if err != nil { return nil, E.Cause(err, "parse inbound[", i, "]") } inbounds = append(inbounds, in) } for i, outboundOptions := range options.Outbounds { var out adapter.Outbound var tag string if outboundOptions.Tag != "" { tag = outboundOptions.Tag } else { tag = F.ToString(i) } out, err = outbound.New( ctx, router, logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")), tag, outboundOptions) if err != nil { return nil, E.Cause(err, "parse outbound[", i, "]") } outbounds = append(outbounds, out) } err = router.Initialize(inbounds, outbounds, func() adapter.Outbound { out, oErr := outbound.New(ctx, router, logFactory.NewLogger("outbound/direct"), "direct", option.Outbound{Type: "direct", Tag: "default"}) common.Must(oErr) outbounds = append(outbounds, out) return out }) if err != nil { return nil, err } if options.PlatformInterface != nil { err = options.PlatformInterface.Initialize(ctx, router) if err != nil { return nil, E.Cause(err, "initialize platform interface") } } preServices1 := make(map[string]adapter.Service) preServices2 := make(map[string]adapter.Service) postServices := make(map[string]adapter.Service) if needCacheFile { cacheFile := service.FromContext[adapter.CacheFile](ctx) if cacheFile == nil { cacheFile = cachefile.New(ctx, common.PtrValueOrDefault(experimentalOptions.CacheFile)) service.MustRegister[adapter.CacheFile](ctx, cacheFile) } preServices1["cache file"] = cacheFile } if needClashAPI { clashAPIOptions := common.PtrValueOrDefault(experimentalOptions.ClashAPI) clashAPIOptions.ModeList = experimental.CalculateClashModeList(options.Options) clashServer, err := experimental.NewClashServer(ctx, router, logFactory.(log.ObservableFactory), clashAPIOptions) if err != nil { return nil, E.Cause(err, "create clash api server") } router.SetClashServer(clashServer) preServices2["clash api"] = clashServer } if needV2RayAPI { v2rayServer, err := experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), common.PtrValueOrDefault(experimentalOptions.V2RayAPI)) if err != nil { return nil, E.Cause(err, "create v2ray api server") } router.SetV2RayServer(v2rayServer) preServices2["v2ray api"] = v2rayServer } return &Box{ router: router, inbounds: inbounds, outbounds: outbounds, createdAt: createdAt, logFactory: logFactory, logger: logFactory.Logger(), preServices1: preServices1, preServices2: preServices2, postServices: postServices, done: make(chan struct{}), }, nil } func (s *Box) PreStart() error { err := s.preStart() if err != nil { // TODO: remove catch error defer func() { v := recover() if v != nil { println(err.Error()) debug.PrintStack() panic("panic on early close: " + fmt.Sprint(v)) } }() s.Close() return err } s.logger.Info("sing-box pre-started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)") return nil } func (s *Box) Start() error { err := s.start() if err != nil { // TODO: remove catch error defer func() { v := recover() if v != nil { println(err.Error()) debug.PrintStack() println("panic on early start: " + fmt.Sprint(v)) } }() s.Close() return err } s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)") return nil } func (s *Box) preStart() error { monitor := taskmonitor.New(s.logger, C.StartTimeout) monitor.Start("start logger") err := s.logFactory.Start() monitor.Finish() if err != nil { return E.Cause(err, "start logger") } for serviceName, service := range s.preServices1 { if preService, isPreService := service.(adapter.PreStarter); isPreService { monitor.Start("pre-start ", serviceName) err := preService.PreStart() monitor.Finish() if err != nil { return E.Cause(err, "pre-start ", serviceName) } } } for serviceName, service := range s.preServices2 { if preService, isPreService := service.(adapter.PreStarter); isPreService { monitor.Start("pre-start ", serviceName) err := preService.PreStart() monitor.Finish() if err != nil { return E.Cause(err, "pre-start ", serviceName) } } } err = s.router.PreStart() if err != nil { return E.Cause(err, "pre-start router") } err = s.startOutbounds() if err != nil { return err } return s.router.Start() } func (s *Box) start() error { err := s.preStart() if err != nil { return err } for serviceName, service := range s.preServices1 { err = service.Start() if err != nil { return E.Cause(err, "start ", serviceName) } } for serviceName, service := range s.preServices2 { err = service.Start() if err != nil { return E.Cause(err, "start ", serviceName) } } for i, in := range s.inbounds { var tag string if in.Tag() == "" { tag = F.ToString(i) } else { tag = in.Tag() } err = in.Start() if err != nil { return E.Cause(err, "initialize inbound/", in.Type(), "[", tag, "]") } } err = s.postStart() if err != nil { return err } return s.router.Cleanup() } func (s *Box) postStart() error { for serviceName, service := range s.postServices { err := service.Start() if err != nil { return E.Cause(err, "start ", serviceName) } } // TODO: reorganize ALL start order for _, out := range s.outbounds { if lateOutbound, isLateOutbound := out.(adapter.PostStarter); isLateOutbound { err := lateOutbound.PostStart() if err != nil { return E.Cause(err, "post-start outbound/", out.Tag()) } } } err := s.router.PostStart() if err != nil { return err } for _, in := range s.inbounds { if lateInbound, isLateInbound := in.(adapter.PostStarter); isLateInbound { err = lateInbound.PostStart() if err != nil { return E.Cause(err, "post-start inbound/", in.Tag()) } } } return nil } func (s *Box) Close() error { select { case <-s.done: return os.ErrClosed default: close(s.done) } monitor := taskmonitor.New(s.logger, C.StopTimeout) var errors error for serviceName, service := range s.postServices { monitor.Start("close ", serviceName) errors = E.Append(errors, service.Close(), func(err error) error { return E.Cause(err, "close ", serviceName) }) monitor.Finish() } for i, in := range s.inbounds { monitor.Start("close inbound/", in.Type(), "[", i, "]") errors = E.Append(errors, in.Close(), func(err error) error { return E.Cause(err, "close inbound/", in.Type(), "[", i, "]") }) monitor.Finish() } for i, out := range s.outbounds { monitor.Start("close outbound/", out.Type(), "[", i, "]") errors = E.Append(errors, common.Close(out), func(err error) error { return E.Cause(err, "close outbound/", out.Type(), "[", i, "]") }) monitor.Finish() } monitor.Start("close router") if err := common.Close(s.router); err != nil { errors = E.Append(errors, err, func(err error) error { return E.Cause(err, "close router") }) } monitor.Finish() for serviceName, service := range s.preServices1 { monitor.Start("close ", serviceName) errors = E.Append(errors, service.Close(), func(err error) error { return E.Cause(err, "close ", serviceName) }) monitor.Finish() } for serviceName, service := range s.preServices2 { monitor.Start("close ", serviceName) errors = E.Append(errors, service.Close(), func(err error) error { return E.Cause(err, "close ", serviceName) }) monitor.Finish() } if err := common.Close(s.logFactory); err != nil { errors = E.Append(errors, err, func(err error) error { return E.Cause(err, "close logger") }) } return errors } func (s *Box) Router() adapter.Router { return s.router }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/box_outbound.go
Bcore/windows/resources/sing-box-main/box_outbound.go
package box import ( "strings" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/taskmonitor" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" ) func (s *Box) startOutbounds() error { monitor := taskmonitor.New(s.logger, C.StartTimeout) outboundTags := make(map[adapter.Outbound]string) outbounds := make(map[string]adapter.Outbound) for i, outboundToStart := range s.outbounds { var outboundTag string if outboundToStart.Tag() == "" { outboundTag = F.ToString(i) } else { outboundTag = outboundToStart.Tag() } if _, exists := outbounds[outboundTag]; exists { return E.New("outbound tag ", outboundTag, " duplicated") } outboundTags[outboundToStart] = outboundTag outbounds[outboundTag] = outboundToStart } started := make(map[string]bool) for { canContinue := false startOne: for _, outboundToStart := range s.outbounds { outboundTag := outboundTags[outboundToStart] if started[outboundTag] { continue } dependencies := outboundToStart.Dependencies() for _, dependency := range dependencies { if !started[dependency] { continue startOne } } started[outboundTag] = true canContinue = true if starter, isStarter := outboundToStart.(interface { Start() error }); isStarter { monitor.Start("initialize outbound/", outboundToStart.Type(), "[", outboundTag, "]") err := starter.Start() monitor.Finish() if err != nil { return E.Cause(err, "initialize outbound/", outboundToStart.Type(), "[", outboundTag, "]") } } } if len(started) == len(s.outbounds) { break } if canContinue { continue } currentOutbound := common.Find(s.outbounds, func(it adapter.Outbound) bool { return !started[outboundTags[it]] }) var lintOutbound func(oTree []string, oCurrent adapter.Outbound) error lintOutbound = func(oTree []string, oCurrent adapter.Outbound) error { problemOutboundTag := common.Find(oCurrent.Dependencies(), func(it string) bool { return !started[it] }) if common.Contains(oTree, problemOutboundTag) { return E.New("circular outbound dependency: ", strings.Join(oTree, " -> "), " -> ", problemOutboundTag) } problemOutbound := outbounds[problemOutboundTag] if problemOutbound == nil { return E.New("dependency[", problemOutboundTag, "] not found for outbound[", outboundTags[oCurrent], "]") } return lintOutbound(append(oTree, problemOutboundTag), problemOutbound) } return lintOutbound([]string{outboundTags[currentOutbound]}, currentOutbound) } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/debug.go
Bcore/windows/resources/sing-box-main/debug.go
package box import ( "runtime/debug" "github.com/sagernet/sing-box/common/conntrack" "github.com/sagernet/sing-box/option" ) func applyDebugOptions(options option.DebugOptions) { applyDebugListenOption(options) if options.GCPercent != nil { debug.SetGCPercent(*options.GCPercent) } if options.MaxStack != nil { debug.SetMaxStack(*options.MaxStack) } if options.MaxThreads != nil { debug.SetMaxThreads(*options.MaxThreads) } if options.PanicOnFault != nil { debug.SetPanicOnFault(*options.PanicOnFault) } if options.TraceBack != "" { debug.SetTraceback(options.TraceBack) } if options.MemoryLimit != 0 { debug.SetMemoryLimit(int64(float64(options.MemoryLimit) / 1.5)) conntrack.MemoryLimit = uint64(options.MemoryLimit) } if options.OOMKiller != nil { conntrack.KillerEnabled = *options.OOMKiller } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/debug_unix.go
Bcore/windows/resources/sing-box-main/debug_unix.go
//go:build linux || darwin package box import ( "runtime" "syscall" ) func rusageMaxRSS() float64 { ru := syscall.Rusage{} err := syscall.Getrusage(syscall.RUSAGE_SELF, &ru) if err != nil { return 0 } rss := float64(ru.Maxrss) if runtime.GOOS == "darwin" || runtime.GOOS == "ios" { rss /= 1 << 20 // ru_maxrss is bytes on darwin } else { // ru_maxrss is kilobytes elsewhere (linux, openbsd, etc) rss /= 1 << 10 } return rss }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/debug_stub.go
Bcore/windows/resources/sing-box-main/debug_stub.go
//go:build !(linux || darwin) package box func rusageMaxRSS() float64 { return -1 }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/debug_http.go
Bcore/windows/resources/sing-box-main/debug_http.go
package box import ( "net/http" "net/http/pprof" "runtime" "runtime/debug" "strings" "github.com/sagernet/sing-box/common/humanize" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" "github.com/sagernet/sing/common/json/badjson" "github.com/go-chi/chi/v5" ) var debugHTTPServer *http.Server func applyDebugListenOption(options option.DebugOptions) { if debugHTTPServer != nil { debugHTTPServer.Close() debugHTTPServer = nil } if options.Listen == "" { return } r := chi.NewMux() r.Route("/debug", func(r chi.Router) { r.Get("/gc", func(writer http.ResponseWriter, request *http.Request) { writer.WriteHeader(http.StatusNoContent) go debug.FreeOSMemory() }) r.Get("/memory", func(writer http.ResponseWriter, request *http.Request) { var memStats runtime.MemStats runtime.ReadMemStats(&memStats) var memObject badjson.JSONObject memObject.Put("heap", humanize.MemoryBytes(memStats.HeapInuse)) memObject.Put("stack", humanize.MemoryBytes(memStats.StackInuse)) memObject.Put("idle", humanize.MemoryBytes(memStats.HeapIdle-memStats.HeapReleased)) memObject.Put("goroutines", runtime.NumGoroutine()) memObject.Put("rss", rusageMaxRSS()) encoder := json.NewEncoder(writer) encoder.SetIndent("", " ") encoder.Encode(memObject) }) r.Route("/pprof", func(r chi.Router) { r.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { if !strings.HasSuffix(request.URL.Path, "/") { http.Redirect(writer, request, request.URL.Path+"/", http.StatusMovedPermanently) } else { pprof.Index(writer, request) } }) r.HandleFunc("/*", pprof.Index) r.HandleFunc("/cmdline", pprof.Cmdline) r.HandleFunc("/profile", pprof.Profile) r.HandleFunc("/symbol", pprof.Symbol) r.HandleFunc("/trace", pprof.Trace) }) }) debugHTTPServer = &http.Server{ Addr: options.Listen, Handler: r, } go func() { err := debugHTTPServer.ListenAndServe() if err != nil && !E.IsClosed(err) { log.Error(E.Cause(err, "serve debug HTTP server")) } }() }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/time.go
Bcore/windows/resources/sing-box-main/constant/time.go
package constant const TimeLayout = "2006-01-02 15:04:05 -0700"
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/proxy.go
Bcore/windows/resources/sing-box-main/constant/proxy.go
package constant const ( TypeTun = "tun" TypeRedirect = "redirect" TypeTProxy = "tproxy" TypeDirect = "direct" TypeBlock = "block" TypeDNS = "dns" TypeSOCKS = "socks" TypeHTTP = "http" TypeMixed = "mixed" TypeShadowsocks = "shadowsocks" TypeVMess = "vmess" TypeTrojan = "trojan" TypeNaive = "naive" TypeWireGuard = "wireguard" TypeHysteria = "hysteria" TypeTor = "tor" TypeSSH = "ssh" TypeShadowTLS = "shadowtls" TypeShadowsocksR = "shadowsocksr" TypeVLESS = "vless" TypeTUIC = "tuic" TypeHysteria2 = "hysteria2" ) const ( TypeSelector = "selector" TypeURLTest = "urltest" ) func ProxyDisplayName(proxyType string) string { switch proxyType { case TypeTun: return "TUN" case TypeRedirect: return "Redirect" case TypeTProxy: return "TProxy" case TypeDirect: return "Direct" case TypeBlock: return "Block" case TypeDNS: return "DNS" case TypeSOCKS: return "SOCKS" case TypeHTTP: return "HTTP" case TypeMixed: return "Mixed" case TypeShadowsocks: return "Shadowsocks" case TypeVMess: return "VMess" case TypeTrojan: return "Trojan" case TypeNaive: return "Naive" case TypeWireGuard: return "WireGuard" case TypeHysteria: return "Hysteria" case TypeTor: return "Tor" case TypeSSH: return "SSH" case TypeShadowTLS: return "ShadowTLS" case TypeShadowsocksR: return "ShadowsocksR" case TypeVLESS: return "VLESS" case TypeTUIC: return "TUIC" case TypeHysteria2: return "Hysteria2" case TypeSelector: return "Selector" case TypeURLTest: return "URLTest" default: return "Unknown" } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/path.go
Bcore/windows/resources/sing-box-main/constant/path.go
package constant import ( "os" "path/filepath" "github.com/sagernet/sing/common/rw" ) const dirName = "sing-box" var resourcePaths []string func FindPath(name string) (string, bool) { name = os.ExpandEnv(name) if rw.IsFile(name) { return name, true } for _, dir := range resourcePaths { if path := filepath.Join(dir, dirName, name); rw.IsFile(path) { return path, true } if path := filepath.Join(dir, name); rw.IsFile(path) { return path, true } } return name, false } func init() { resourcePaths = append(resourcePaths, ".") if home := os.Getenv("HOME"); home != "" { resourcePaths = append(resourcePaths, home) } if userConfigDir, err := os.UserConfigDir(); err == nil { resourcePaths = append(resourcePaths, userConfigDir) } if userCacheDir, err := os.UserCacheDir(); err == nil { resourcePaths = append(resourcePaths, userCacheDir) } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/path_unix.go
Bcore/windows/resources/sing-box-main/constant/path_unix.go
//go:build unix || linux package constant import ( "os" ) func init() { resourcePaths = append(resourcePaths, "/etc") resourcePaths = append(resourcePaths, "/usr/share") resourcePaths = append(resourcePaths, "/usr/local/etc") resourcePaths = append(resourcePaths, "/usr/local/share") if homeDir := os.Getenv("HOME"); homeDir != "" { resourcePaths = append(resourcePaths, homeDir+"/.local/share") } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/speed.go
Bcore/windows/resources/sing-box-main/constant/speed.go
package constant const MbpsToBps = 125000
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/protocol.go
Bcore/windows/resources/sing-box-main/constant/protocol.go
package constant const ( ProtocolTLS = "tls" ProtocolHTTP = "http" ProtocolQUIC = "quic" ProtocolDNS = "dns" ProtocolSTUN = "stun" ProtocolBitTorrent = "bittorrent" ProtocolDTLS = "dtls" ProtocolSSH = "ssh" ProtocolRDP = "rdp" ) const ( ClientChromium = "chromium" ClientSafari = "safari" ClientFirefox = "firefox" ClientQUICGo = "quic-go" ClientUnknown = "unknown" )
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/v2ray.go
Bcore/windows/resources/sing-box-main/constant/v2ray.go
package constant const ( V2RayTransportTypeHTTP = "http" V2RayTransportTypeWebsocket = "ws" V2RayTransportTypeQUIC = "quic" V2RayTransportTypeGRPC = "grpc" V2RayTransportTypeHTTPUpgrade = "httpupgrade" )
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/dns.go
Bcore/windows/resources/sing-box-main/constant/dns.go
package constant const ( DNSProviderAliDNS = "alidns" DNSProviderCloudflare = "cloudflare" )
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/timeout.go
Bcore/windows/resources/sing-box-main/constant/timeout.go
package constant import "time" const ( TCPKeepAliveInitial = 10 * time.Minute TCPKeepAliveInterval = 75 * time.Second TCPTimeout = 5 * time.Second ReadPayloadTimeout = 300 * time.Millisecond DNSTimeout = 10 * time.Second QUICTimeout = 30 * time.Second STUNTimeout = 15 * time.Second UDPTimeout = 5 * time.Minute DefaultURLTestInterval = 3 * time.Minute DefaultURLTestIdleTimeout = 30 * time.Minute StartTimeout = 10 * time.Second StopTimeout = 5 * time.Second FatalStopTimeout = 10 * time.Second FakeIPMetadataSaveInterval = 10 * time.Second )
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/cgo.go
Bcore/windows/resources/sing-box-main/constant/cgo.go
//go:build cgo package constant const CGO_ENABLED = true
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/err.go
Bcore/windows/resources/sing-box-main/constant/err.go
package constant import E "github.com/sagernet/sing/common/exceptions" var ErrTLSRequired = E.New("TLS required") var ErrQUICNotIncluded = E.New(`QUIC is not included in this build, rebuild with -tags with_quic`)
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/quic.go
Bcore/windows/resources/sing-box-main/constant/quic.go
//go:build with_quic package constant const WithQUIC = true
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/version.go
Bcore/windows/resources/sing-box-main/constant/version.go
package constant var Version = "unknown"
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/dhcp.go
Bcore/windows/resources/sing-box-main/constant/dhcp.go
package constant import "time" const ( DHCPTTL = time.Hour DHCPTimeout = time.Minute )
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/cgo_disabled.go
Bcore/windows/resources/sing-box-main/constant/cgo_disabled.go
//go:build !cgo package constant const CGO_ENABLED = false
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/os.go
Bcore/windows/resources/sing-box-main/constant/os.go
package constant import ( "github.com/sagernet/sing-box/constant/goos" ) const IsAndroid = goos.IsAndroid == 1 const IsDarwin = goos.IsDarwin == 1 const IsDragonfly = goos.IsDragonfly == 1 const IsFreebsd = goos.IsFreebsd == 1 const IsHurd = goos.IsHurd == 1 const IsIllumos = goos.IsIllumos == 1 const IsIos = goos.IsIos == 1 const IsJs = goos.IsJs == 1 const IsLinux = goos.IsLinux == 1 || goos.IsAndroid == 1 const IsNacl = goos.IsNacl == 1 const IsNetbsd = goos.IsNetbsd == 1 const IsOpenbsd = goos.IsOpenbsd == 1 const IsPlan9 = goos.IsPlan9 == 1 const IsSolaris = goos.IsSolaris == 1 const IsWindows = goos.IsWindows == 1 const IsZos = goos.IsZos == 1
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/rule.go
Bcore/windows/resources/sing-box-main/constant/rule.go
package constant const ( RuleTypeDefault = "default" RuleTypeLogical = "logical" ) const ( LogicalTypeAnd = "and" LogicalTypeOr = "or" ) const ( RuleSetTypeInline = "inline" RuleSetTypeLocal = "local" RuleSetTypeRemote = "remote" RuleSetFormatSource = "source" RuleSetFormatBinary = "binary" ) const ( RuleSetVersion1 = 1 + iota RuleSetVersion2 )
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/quic_stub.go
Bcore/windows/resources/sing-box-main/constant/quic_stub.go
//go:build !with_quic package constant const WithQUIC = false
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_freebsd.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_freebsd.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build freebsd package goos const GOOS = `freebsd` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 1 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_plan9.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_plan9.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build plan9 package goos const GOOS = `plan9` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 1 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_aix.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_aix.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build aix package goos const GOOS = `aix` const IsAix = 1 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_ios.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_ios.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build ios package goos const GOOS = `ios` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 1 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_openbsd.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_openbsd.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build openbsd package goos const GOOS = `openbsd` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 1 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_linux.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_linux.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build !android && linux package goos const GOOS = `linux` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 1 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_android.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_android.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build android package goos const GOOS = `android` const IsAix = 0 const IsAndroid = 1 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/goos.go
Bcore/windows/resources/sing-box-main/constant/goos/goos.go
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package goos contains GOOS-specific constants. package goos // The next line makes 'go generate' write the zgoos*.go files with // per-OS information, including constants named Is$GOOS for every // known GOOS. The constant is 1 on the current system, 0 otherwise; // multiplying by them is useful for defining GOOS-specific constants. //go:generate go run gengoos.go
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_dragonfly.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_dragonfly.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build dragonfly package goos const GOOS = `dragonfly` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 1 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_solaris.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_solaris.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build !illumos && solaris package goos const GOOS = `solaris` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 1 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_hurd.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_hurd.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build hurd package goos const GOOS = `hurd` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 1 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_js.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_js.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build js package goos const GOOS = `js` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 1 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_netbsd.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_netbsd.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build netbsd package goos const GOOS = `netbsd` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 1 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_windows.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_windows.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build windows package goos const GOOS = `windows` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 1 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_illumos.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_illumos.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build illumos package goos const GOOS = `illumos` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 1 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 0
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/gengoos.go
Bcore/windows/resources/sing-box-main/constant/goos/gengoos.go
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build ignore package main import ( "bytes" "fmt" "log" "os" "strconv" "strings" ) var gooses []string func main() { data, err := os.ReadFile("../../go/build/syslist.go") if err != nil { log.Fatal(err) } const goosPrefix = `const goosList = ` for _, line := range strings.Split(string(data), "\n") { if strings.HasPrefix(line, goosPrefix) { text, err := strconv.Unquote(strings.TrimPrefix(line, goosPrefix)) if err != nil { log.Fatalf("parsing goosList: %v", err) } gooses = strings.Fields(text) } } for _, target := range gooses { if target == "nacl" { continue } var tags []string if target == "linux" { tags = append(tags, "!android") // must explicitly exclude android for linux } if target == "solaris" { tags = append(tags, "!illumos") // must explicitly exclude illumos for solaris } if target == "darwin" { tags = append(tags, "!ios") // must explicitly exclude ios for darwin } tags = append(tags, target) // must explicitly include target for bootstrapping purposes var buf bytes.Buffer fmt.Fprintf(&buf, "// Code generated by gengoos.go using 'go generate'. DO NOT EDIT.\n\n") fmt.Fprintf(&buf, "//go:build %s\n", strings.Join(tags, " && ")) fmt.Fprintf(&buf, "package goos\n\n") fmt.Fprintf(&buf, "const GOOS = `%s`\n\n", target) for _, goos := range gooses { value := 0 if goos == target { value = 1 } fmt.Fprintf(&buf, "const Is%s = %d\n", strings.Title(goos), value) } err := os.WriteFile("zgoos_"+target+".go", buf.Bytes(), 0o666) if err != nil { log.Fatal(err) } } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/constant/goos/zgoos_zos.go
Bcore/windows/resources/sing-box-main/constant/goos/zgoos_zos.go
// Code generated by gengoos.go using 'go generate'. DO NOT EDIT. //go:build zos package goos const GOOS = `zos` const IsAix = 0 const IsAndroid = 0 const IsDarwin = 0 const IsDragonfly = 0 const IsFreebsd = 0 const IsHurd = 0 const IsIllumos = 0 const IsIos = 0 const IsJs = 0 const IsLinux = 0 const IsNacl = 0 const IsNetbsd = 0 const IsOpenbsd = 0 const IsPlan9 = 0 const IsSolaris = 0 const IsWindows = 0 const IsZos = 1
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false