Commit 06ce178b authored by son ngo's avatar son ngo

init prj

parents
Pipeline #1976 failed with stages
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/otel_microservice_test.iml" filepath="$PROJECT_DIR$/.idea/otel_microservice_test.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
OTLP_ENDPOINT=localhost:4318
\ No newline at end of file
package endpoint
import (
"context"
"github.com/go-kit/kit/endpoint"
"go.opentelemetry.io/otel/trace"
"otel_microservice_test/service"
)
type LogEndpoints struct {
NewLogEndpoint endpoint.Endpoint
}
func MakeServerLogEndpoint(logsvc service.LogService, tracer trace.Tracer) LogEndpoints {
return LogEndpoints{
NewLogEndpoint: MakeLogEndpoint(logsvc, tracer),
}
}
func MakeLogEndpoint(logsvc service.LogService, tracer trace.Tracer) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
ctx, span := tracer.Start(context.Background(), "HTTP GET /endpoint/makelog")
defer span.End()
req := request.(service.LogReq)
logRes, err := logsvc.GetLog(ctx, req.Key, tracer)
if err != nil {
return nil, err
}
return service.LogRes{
Id: logRes.Id,
Key: logRes.Key,
Value: logRes.Value,
}, nil
}
}
func (l LogEndpoints) GetLog(ctx context.Context, key string, tracer trace.Tracer) (service.LogRes, error) {
ctx2, span := tracer.Start(ctx, "HTTP GET /endpoint/getlog")
defer span.End()
res, err := l.NewLogEndpoint(ctx2, service.LogReq{
Key: key,
})
if err != nil {
return service.LogRes{}, err
}
response := res.(service.LogRes)
return response, err
}
package endpoint
import (
"context"
"github.com/go-kit/kit/endpoint"
"go.opentelemetry.io/otel/trace"
"otel_microservice_test/service"
)
type TestEndpoint struct {
TestEndpoint endpoint.Endpoint
}
func MakeServerEndpoint(s service.Service, tracer trace.Tracer) TestEndpoint {
return TestEndpoint{
TestEndpoint: MakeTestEndpoint(s, tracer),
}
}
func MakeTestEndpoint(s service.Service, tracer trace.Tracer) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
ctx, span := tracer.Start(context.Background(), "HTTP GET /endpoint/test")
defer span.End()
err = s.Test(ctx)
if err != nil {
return nil, err
}
return Response{
Message: "Test server",
Err: nil,
}, nil
}
}
func (r Response) Failed() error { return r.Err }
type Response struct {
Message string `json:"message"`
Err error `json:"err"`
}
module otel_microservice_test
go 1.22
require (
github.com/go-kit/kit v0.13.0
github.com/sony/gobreaker v0.4.1
go.opentelemetry.io/otel v1.26.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.26.0
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.26.0
go.opentelemetry.io/otel/sdk v1.26.0
go.opentelemetry.io/otel/trace v1.26.0
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11
google.golang.org/grpc v1.63.2
google.golang.org/protobuf v1.33.0
)
require (
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/go-kit/log v0.2.0 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/go-logr/logr v1.4.1 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/streadway/handy v0.0.0-20200128134331-0f66f006fb2e // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.26.0 // indirect
go.opentelemetry.io/otel/metric v1.26.0 // indirect
go.opentelemetry.io/proto/otlp v1.2.0 // indirect
golang.org/x/net v0.23.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240401170217-c3f982113cda // indirect
)
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5 h1:rFw4nCn9iMW+Vajsk51NtYIcwSTkXr+JGrMd36kTDJw=
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-kit/kit v0.13.0 h1:OoneCcHKHQ03LfBpoQCUfCluwd2Vt3ohz+kvbJneZAU=
github.com/go-kit/kit v0.13.0/go.mod h1:phqEHMMUbyrCFCTgH48JueqrM3md2HcAZ8N3XE4FKDg=
github.com/go-kit/log v0.2.0 h1:7i2K3eKTos3Vc0enKCfnVcgHh2olr/MyfboYq7cAcFw=
github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0=
github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA=
github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1 h1:/c3QmbOGMGTOumP2iT/rCwB7b0QDGLKzqOmktBjT+Is=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1/go.mod h1:5SN9VR2LTsRFsrEC6FHgRbTWrTHu6tqPeKxEQv15giM=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sony/gobreaker v0.4.1 h1:oMnRNZXX5j85zso6xCPRNPtmAycat+WcoKbklScLDgQ=
github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY=
github.com/streadway/handy v0.0.0-20200128134331-0f66f006fb2e h1:mOtuXaRAbVZsxAHVdPR3IjfmN8T1h2iczJLynhLybf8=
github.com/streadway/handy v0.0.0-20200128134331-0f66f006fb2e/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.opentelemetry.io/otel v1.26.0 h1:LQwgL5s/1W7YiiRwxf03QGnWLb2HW4pLiAhaA5cZXBs=
go.opentelemetry.io/otel v1.26.0/go.mod h1:UmLkJHUAidDval2EICqBMbnAd0/m2vmpf/dAM+fvFs4=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.26.0 h1:1u/AyyOqAWzy+SkPxDpahCNZParHV8Vid1RnI2clyDE=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.26.0/go.mod h1:z46paqbJ9l7c9fIPCXTqTGwhQZ5XoTIsfeFYWboizjs=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.26.0 h1:1wp/gyxsuYtuE/JFxsQRtcCDtMrO2qMvlfXALU5wkzI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.26.0/go.mod h1:gbTHmghkGgqxMomVQQMur1Nba4M0MQ8AYThXDUjsJ38=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.26.0 h1:0W5o9SzoR15ocYHEQfvfipzcNog1lBxOLfnex91Hk6s=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.26.0/go.mod h1:zVZ8nz+VSggWmnh6tTsJqXQ7rU4xLwRtna1M4x5jq58=
go.opentelemetry.io/otel/metric v1.26.0 h1:7S39CLuY5Jgg9CrnA9HHiEjGMF/X2VHvoXGgSllRz30=
go.opentelemetry.io/otel/metric v1.26.0/go.mod h1:SY+rHOI4cEawI9a7N1A4nIg/nTQXe1ccCNWYOJUrpX4=
go.opentelemetry.io/otel/sdk v1.26.0 h1:Y7bumHf5tAiDlRYFmGqetNcLaVUZmh4iYfmGxtmz7F8=
go.opentelemetry.io/otel/sdk v1.26.0/go.mod h1:0p8MXpqLeJ0pzcszQQN4F0S5FVjBLgypeGSngLsmirs=
go.opentelemetry.io/otel/trace v1.26.0 h1:1ieeAUb4y0TE26jUFrCIXKpTuVK7uJGN9/Z/2LP5sQA=
go.opentelemetry.io/otel/trace v1.26.0/go.mod h1:4iDxvGDQuUkHve82hJJ8UqrwswHYsZuWCBllGV2U2y0=
go.opentelemetry.io/proto/otlp v1.2.0 h1:pVeZGk7nXDC9O2hncA6nHldxEjm6LByfA2aN8IOkz94=
go.opentelemetry.io/proto/otlp v1.2.0/go.mod h1:gGpR8txAl5M03pDhMC79G6SdqNV26naRm/KDsgaHD8A=
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 h1:GZokNIeuVkl3aZHJchRrr13WCsols02MLUcz1U9is6M=
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de h1:F6qOa9AZTYJXOUEr4jDysRDLrm4PHePlge4v4TGAlxY=
google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:VUhTRKeHn9wwcdrk73nvdC9gF178Tzhmt/qyaFcPLSo=
google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de h1:jFNzHPIeuzhdRwVhbZdiym9q0ory/xY3sA+v2wPg8I0=
google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:5iCWqnniDlqZHrd3neWVTOwvh/v6s3232omMecelax8=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240401170217-c3f982113cda h1:LI5DOvAxUPMv/50agcLLoo+AdWc1irS9Rzz4vPuD1V4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240401170217-c3f982113cda/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY=
google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM=
google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
package main
import (
"context"
"flag"
"fmt"
"github.com/go-kit/kit/log"
"github.com/joho/godotenv"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
"go.opentelemetry.io/otel/sdk/resource"
oteltrace "go.opentelemetry.io/otel/sdk/trace"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
log2 "log"
"net"
"net/http"
"os"
"otel_microservice_test/endpoint"
"otel_microservice_test/service"
"otel_microservice_test/transport"
"time"
)
var (
tracer trace.Tracer
otlpEndpoint string
)
func init() {
godotenv.Load()
otlpEndpoint = os.Getenv("OTLP_ENDPOINT")
if otlpEndpoint == "" {
log2.Fatalln("You MUST set OTLP_ENDPOINT env variable!")
}
}
func newConsoleExporter() (oteltrace.SpanExporter, error) {
return stdouttrace.New()
}
func newOTLPExporter(ctx context.Context) (oteltrace.SpanExporter, error) {
insecureOpt := otlptracehttp.WithInsecure()
endpointOpt := otlptracehttp.WithEndpoint(otlpEndpoint)
return otlptracehttp.New(ctx, insecureOpt, endpointOpt)
}
func newTraceProvider(exp sdktrace.SpanExporter) *sdktrace.TracerProvider {
r, err := resource.Merge(
resource.Default(),
resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName("service_1"),
),
)
if err != nil {
panic(err)
}
return sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
sdktrace.WithResource(r),
)
}
func Start() (net.Listener, error) {
ctx := context.Background()
//exp, err := newConsoleExporter()
exp, err := newOTLPExporter(ctx)
if err != nil {
log2.Fatalf("failed to initialize exporter: %v", err)
}
tp := newTraceProvider(exp)
defer func() { _ = tp.Shutdown(ctx) }()
otel.SetTracerProvider(tp)
tracer = tp.Tracer("service_1")
httpAddr := flag.String("httpAddr", ":8081", "HTTP listen address")
grpcAddr := flag.String("grpcAddr", ":9085", "GRPC listen address")
flag.Parse()
fmt.Println("httpAddr", *httpAddr)
fmt.Println("grpcAddr", *grpcAddr)
var logger log.Logger
logger = log.NewLogfmtLogger(os.Stderr)
logger = log.With(logger, "caller", log.DefaultCaller)
var logSvc service.LogService
{
conn, err := grpc.Dial(*grpcAddr, grpc.WithInsecure(), grpc.WithTimeout(time.Second))
if err != nil {
logger.Log("during", "connecting proxy", "error", err)
os.Exit(1)
}
defer conn.Close()
logSvc = transport.NewGRPCClient(conn, tracer)
}
var (
svc = service.NewService(tracer)
endpoints = endpoint.MakeServerEndpoint(svc, tracer)
logEndpoint = endpoint.MakeServerLogEndpoint(logSvc, tracer)
httpHandler = transport.NewHTTPHandler(endpoints, logEndpoint, logger, tracer)
)
httpListener, err := net.Listen("tcp", *httpAddr)
if err != nil {
logger.Log("transport", "HTTP", "during", "Listen", "err", err)
os.Exit(1)
return httpListener, err
}
logger.Log("transport", "Http", "addr", *httpAddr)
return httpListener, http.Serve(httpListener, httpHandler)
}
func main() {
httpListener, err := Start()
if err != nil {
httpListener.Close()
}
}
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.1
// protoc v5.27.0--rc1
// source: pb/log.proto
package pb
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type LogReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
}
func (x *LogReq) Reset() {
*x = LogReq{}
if protoimpl.UnsafeEnabled {
mi := &file_pb_log_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *LogReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*LogReq) ProtoMessage() {}
func (x *LogReq) ProtoReflect() protoreflect.Message {
mi := &file_pb_log_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use LogReq.ProtoReflect.Descriptor instead.
func (*LogReq) Descriptor() ([]byte, []int) {
return file_pb_log_proto_rawDescGZIP(), []int{0}
}
func (x *LogReq) GetKey() string {
if x != nil {
return x.Key
}
return ""
}
type LogRes struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"`
Value string `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *LogRes) Reset() {
*x = LogRes{}
if protoimpl.UnsafeEnabled {
mi := &file_pb_log_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *LogRes) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*LogRes) ProtoMessage() {}
func (x *LogRes) ProtoReflect() protoreflect.Message {
mi := &file_pb_log_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use LogRes.ProtoReflect.Descriptor instead.
func (*LogRes) Descriptor() ([]byte, []int) {
return file_pb_log_proto_rawDescGZIP(), []int{1}
}
func (x *LogRes) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *LogRes) GetKey() string {
if x != nil {
return x.Key
}
return ""
}
func (x *LogRes) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
var File_pb_log_proto protoreflect.FileDescriptor
var file_pb_log_proto_rawDesc = []byte{
0x0a, 0x0c, 0x70, 0x62, 0x2f, 0x6c, 0x6f, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x02,
0x70, 0x62, 0x22, 0x1a, 0x0a, 0x06, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x71, 0x12, 0x10, 0x0a, 0x03,
0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x22, 0x40,
0x0a, 0x06, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x73, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01,
0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18,
0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61,
0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65,
0x32, 0x2e, 0x0a, 0x0a, 0x4c, 0x6f, 0x67, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x20,
0x0a, 0x06, 0x47, 0x65, 0x74, 0x4c, 0x6f, 0x67, 0x12, 0x0a, 0x2e, 0x70, 0x62, 0x2e, 0x4c, 0x6f,
0x67, 0x52, 0x65, 0x71, 0x1a, 0x0a, 0x2e, 0x70, 0x62, 0x2e, 0x4c, 0x6f, 0x67, 0x52, 0x65, 0x73,
0x42, 0x07, 0x5a, 0x05, 0x2e, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x33,
}
var (
file_pb_log_proto_rawDescOnce sync.Once
file_pb_log_proto_rawDescData = file_pb_log_proto_rawDesc
)
func file_pb_log_proto_rawDescGZIP() []byte {
file_pb_log_proto_rawDescOnce.Do(func() {
file_pb_log_proto_rawDescData = protoimpl.X.CompressGZIP(file_pb_log_proto_rawDescData)
})
return file_pb_log_proto_rawDescData
}
var file_pb_log_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_pb_log_proto_goTypes = []interface{}{
(*LogReq)(nil), // 0: pb.LogReq
(*LogRes)(nil), // 1: pb.LogRes
}
var file_pb_log_proto_depIdxs = []int32{
0, // 0: pb.LogService.GetLog:input_type -> pb.LogReq
1, // 1: pb.LogService.GetLog:output_type -> pb.LogRes
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_pb_log_proto_init() }
func file_pb_log_proto_init() {
if File_pb_log_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_pb_log_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*LogReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_pb_log_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*LogRes); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_pb_log_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_pb_log_proto_goTypes,
DependencyIndexes: file_pb_log_proto_depIdxs,
MessageInfos: file_pb_log_proto_msgTypes,
}.Build()
File_pb_log_proto = out.File
file_pb_log_proto_rawDesc = nil
file_pb_log_proto_goTypes = nil
file_pb_log_proto_depIdxs = nil
}
syntax = "proto3";
package pb;
option go_package = "../pb";
import "google/protobuf/descriptor.proto";
service LogService {
rpc GetLog(LogReq) returns (LogRes);
}
message LogReq {
string key = 1;
}
message LogRes {
string id = 1;
string key = 2;
string value = 3;
}
\ No newline at end of file
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v5.27.0--rc1
// source: pb/log.proto
package pb
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// LogServiceClient is the client API for LogService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type LogServiceClient interface {
GetLog(ctx context.Context, in *LogReq, opts ...grpc.CallOption) (*LogRes, error)
}
type logServiceClient struct {
cc grpc.ClientConnInterface
}
func NewLogServiceClient(cc grpc.ClientConnInterface) LogServiceClient {
return &logServiceClient{cc}
}
func (c *logServiceClient) GetLog(ctx context.Context, in *LogReq, opts ...grpc.CallOption) (*LogRes, error) {
out := new(LogRes)
err := c.cc.Invoke(ctx, "/pb.LogService/GetLog", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// LogServiceServer is the server API for LogService service.
// All implementations must embed UnimplementedLogServiceServer
// for forward compatibility
type LogServiceServer interface {
GetLog(context.Context, *LogReq) (*LogRes, error)
mustEmbedUnimplementedLogServiceServer()
}
// UnimplementedLogServiceServer must be embedded to have forward compatible implementations.
type UnimplementedLogServiceServer struct {
}
func (UnimplementedLogServiceServer) GetLog(context.Context, *LogReq) (*LogRes, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetLog not implemented")
}
func (UnimplementedLogServiceServer) mustEmbedUnimplementedLogServiceServer() {}
// UnsafeLogServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to LogServiceServer will
// result in compilation errors.
type UnsafeLogServiceServer interface {
mustEmbedUnimplementedLogServiceServer()
}
func RegisterLogServiceServer(s grpc.ServiceRegistrar, srv LogServiceServer) {
s.RegisterService(&LogService_ServiceDesc, srv)
}
func _LogService_GetLog_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(LogReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LogServiceServer).GetLog(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pb.LogService/GetLog",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LogServiceServer).GetLog(ctx, req.(*LogReq))
}
return interceptor(ctx, in, info, handler)
}
// LogService_ServiceDesc is the grpc.ServiceDesc for LogService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var LogService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "pb.LogService",
HandlerType: (*LogServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetLog",
Handler: _LogService_GetLog_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "pb/log.proto",
}
package service
import (
"context"
"go.opentelemetry.io/otel/trace"
)
type LogService interface {
GetLog(ctx context.Context, key string, tracer trace.Tracer) (LogRes, error)
}
type LogRes struct {
Id string
Key string
Value string
}
type LogReq struct {
Key string
}
package service
import (
"context"
"go.opentelemetry.io/otel/trace"
"time"
)
type Service interface {
Test(ctx context.Context) error
}
type service struct {
tracer trace.Tracer
}
func NewService(tracer trace.Tracer) Service {
return &service{
tracer: tracer,
}
}
func (s *service) Test(ctx context.Context) error {
ctx, span := s.tracer.Start(ctx, "HTTP GET /service/test")
defer span.End()
time.Sleep(time.Millisecond * 2000)
s.Test2(ctx)
return nil
}
func (s *service) Test2(ctx context.Context) {
_, span := s.tracer.Start(ctx, "HTTP GET /service/test2")
defer span.End()
time.Sleep(time.Second)
}
package transport
import (
"context"
grpcTransport "github.com/go-kit/kit/transport/grpc"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"otel_microservice_test/endpoint"
"otel_microservice_test/pb"
"otel_microservice_test/service"
)
func NewGRPCClient(conn *grpc.ClientConn, tracer trace.Tracer) service.LogService {
var options []grpcTransport.ClientOption
logEndpoint := grpcTransport.NewClient(
conn,
"pb.LogService",
"GetLog",
encodeGRPCNewLogRequest,
decodeGRPCNewLogResponse,
pb.LogRes{},
options...,
).Endpoint()
return endpoint.LogEndpoints{
NewLogEndpoint: logEndpoint,
}
}
func encodeGRPCNewLogRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(service.LogReq)
return &pb.LogReq{
Key: req.Key,
}, nil
}
func decodeGRPCNewLogResponse(_ context.Context, response interface{}) (interface{}, error) {
resp := response.(*pb.LogRes)
return service.LogRes{
Id: resp.Id,
Key: resp.Key,
Value: resp.Value,
}, nil
}
package transport
import (
"context"
"encoding/json"
"github.com/go-kit/kit/endpoint"
log2 "github.com/go-kit/kit/log"
"github.com/go-kit/kit/transport"
httpTransport "github.com/go-kit/kit/transport/http"
"go.opentelemetry.io/otel/trace"
"net/http"
endpoint2 "otel_microservice_test/endpoint"
"otel_microservice_test/service"
)
func NewHTTPHandler(endpoints endpoint2.TestEndpoint, logEndpoint endpoint2.LogEndpoints, logger log2.Logger, tracer trace.Tracer) http.Handler {
mux := http.NewServeMux()
options := []httpTransport.ServerOption{
httpTransport.ServerErrorEncoder(errorEncoder),
httpTransport.ServerErrorHandler(transport.NewLogErrorHandler(logger)),
}
mux.Handle("/test", httpTransport.NewServer(
endpoints.TestEndpoint,
decodeTestReq(tracer),
encodeTestRes,
options...,
))
mux.Handle("/log", httpTransport.NewServer(
logEndpoint.NewLogEndpoint,
decodeHTTPLogReq,
encodeHTTPLogRes,
options...,
))
return mux
}
// ================================ //DECODER// ================================ //
func decodeTestReq(tracer trace.Tracer) httpTransport.DecodeRequestFunc {
return func(_ context.Context, r *http.Request) (interface{}, error) {
return nil, nil
}
}
func decodeHTTPLogReq(_ context.Context, r *http.Request) (interface{}, error) {
var req service.LogReq
err := json.NewDecoder(r.Body).Decode(&req)
return req, err
}
// ================================ //ENCODER// ================================ //
func encodeTestRes(ctx context.Context, w http.ResponseWriter, response interface{}) error {
if f, ok := response.(endpoint.Failer); ok && f.Failed() != nil {
errorEncoder(ctx, f.Failed(), w)
return nil
}
return json.NewEncoder(w).Encode(response)
}
func encodeHTTPLogRes(ctx context.Context, w http.ResponseWriter, response interface{}) error {
if f, ok := response.(endpoint.Failer); ok && f.Failed() != nil {
errorEncoder(ctx, f.Failed(), w)
return nil
}
return json.NewEncoder(w).Encode(response)
}
func errorEncoder(_ context.Context, err error, w http.ResponseWriter) {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(errorWrapper{
Error: err.Error(),
Code: 500,
})
}
type errorWrapper struct {
Error string `json:"error"`
Code int `json:"code"`
}
# This file is maintained automatically by "terraform init".
# Manual edits may be lost in future updates.
provider "registry.terraform.io/gavinbunney/kubectl" {
version = "1.14.0"
constraints = "1.14.0"
hashes = [
"h1:Ck8Re/28x7VBI5ArFg0VSg1woPu/APm1ZbMuzqUdnPo=",
"zh:0350f3122ff711984bbc36f6093c1fe19043173fad5a904bce27f86afe3cc858",
"zh:07ca36c7aa7533e8325b38232c77c04d6ef1081cb0bac9d56e8ccd51f12f2030",
"zh:0c351afd91d9e994a71fe64bbd1662d0024006b3493bb61d46c23ea3e42a7cf5",
"zh:39f1a0aa1d589a7e815b62b5aa11041040903b061672c4cfc7de38622866cbc4",
"zh:428d3a321043b78e23c91a8d641f2d08d6b97f74c195c654f04d2c455e017de5",
"zh:4baf5b1de2dfe9968cc0f57fd4be5a741deb5b34ee0989519267697af5f3eee5",
"zh:6131a927f9dffa014ab5ca5364ac965fe9b19830d2bbf916a5b2865b956fdfcf",
"zh:c62e0c9fd052cbf68c5c2612af4f6408c61c7e37b615dc347918d2442dd05e93",
"zh:f0beffd7ce78f49ead612e4b1aefb7cb6a461d040428f514f4f9cc4e5698ac65",
]
}
provider "registry.terraform.io/hashicorp/helm" {
version = "2.11.0"
constraints = "2.11.0"
hashes = [
"h1:/bxsVBBNaKwLwKapK7mR0ZrE+jhkThD0lfc6rVBD/kU=",
"zh:013857c88f3e19a4b162344e21dc51891c4ac8b600da8391f7fb2b6d234961e1",
"zh:044fffa233a93cdcf8384afbe9e1ab6c9d0b5b176cbae56ff465eb9611302975",
"zh:208b7cdd4fa3a1b25ae817dc00a9198ef98be0ddc3a577b5b72bc0f006afb997",
"zh:3e8b33f56cfe387277572a92037a1ca1cbe4e3aa6b5c19a8c2431193b07f7865",
"zh:7dd663d5619bd71676899b05b19d36f585189fdabc6b0b03c23579524a8fd9bf",
"zh:ae5329cb3e5bf0b86b02e823aac3ef3bd0d4b1618ff013cd0076dca0be8322e4",
"zh:ba6201695b55d51bedacdb017cb8d03d7a8ada51d0168ac44fef3fa791a85ab4",
"zh:c61285c8b1ba10f50cf94c9dcf98f2f3b720f14906a18be71b9b422279b5d806",
"zh:d522d388246f38b9f329c511ec579b516d212670b954f9dab64efb27e51862af",
"zh:f569b65999264a9416862bca5cd2a6177d94ccb0424f3a4ef424428912b9cb3c",
"zh:f92546e26b670da61437ae2cbd038427c9374ce5f7a78df52193397da90bd997",
"zh:f9ad1407e5c0d5e3474094491025bf100828e8c1a01acdf9591d7dd1eb59f961",
]
}
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
# Kubernetes "kubectl" Provider
![Build Status](https://github.com/gavinbunney/terraform-provider-kubectl/actions/workflows/build.yml/badge.svg) [![user guide](https://img.shields.io/badge/-user%20guide-blue)](https://registry.terraform.io/providers/gavinbunney/kubectl)
This provider is the best way of managing Kubernetes resources in Terraform, by allowing you to use the thing
Kubernetes loves best - yaml!
This core of this provider is the `kubectl_manifest` resource, allowing free-form yaml to be processed and applied against Kubernetes.
This yaml object is then tracked and handles creation, updates and deleted seamlessly - including drift detection!
A set of helpful data resources to process directories of yaml files and inline templating is available.
This `terraform-provider-kubectl` provider has been used by many large Kubernetes installations to completely
manage the lifecycle of Kubernetes resources.
## Installation
### Terraform 0.13+
The provider can be installed and managed automatically by Terraform. Sample `versions.tf` file :
```hcl
terraform {
required_version = ">= 0.13"
required_providers {
kubectl = {
source = "gavinbunney/kubectl"
version = ">= 1.7.0"
}
}
}
```
### Terraform 0.12
#### Install latest version
The following one-liner script will fetch the latest provider version and download it to your `~/.terraform.d/plugins` directory.
```bash
$ mkdir -p ~/.terraform.d/plugins && \
curl -Ls https://api.github.com/repos/gavinbunney/terraform-provider-kubectl/releases/latest \
| jq -r ".assets[] | select(.browser_download_url | contains(\"$(uname -s | tr A-Z a-z)\")) | select(.browser_download_url | contains(\"amd64\")) | .browser_download_url" \
| xargs -n 1 curl -Lo ~/.terraform.d/plugins/terraform-provider-kubectl.zip && \
pushd ~/.terraform.d/plugins/ && \
unzip ~/.terraform.d/plugins/terraform-provider-kubectl.zip -d terraform-provider-kubectl-tmp && \
mv terraform-provider-kubectl-tmp/terraform-provider-kubectl* . && \
chmod +x terraform-provider-kubectl* && \
rm -rf terraform-provider-kubectl-tmp && \
rm -rf terraform-provider-kubectl.zip && \
popd
```
#### Install manually
If you don't want to use the one-liner above, you can download a binary for your system from the [release page](https://github.com/gavinbunney/terraform-provider-kubectl/releases),
then either place it at the root of your Terraform folder or in the Terraform plugin folder on your system.
## Quick Start
```hcl
provider "kubectl" {
host = var.eks_cluster_endpoint
cluster_ca_certificate = base64decode(var.eks_cluster_ca)
token = data.aws_eks_cluster_auth.main.token
load_config_file = false
}
resource "kubectl_manifest" "test" {
yaml_body = <<YAML
apiVersion: couchbase.com/v1
kind: CouchbaseCluster
metadata:
name: name-here-cluster
spec:
baseImage: name-here-image
version: name-here-image-version
authSecret: name-here-operator-secret-name
exposeAdminConsole: true
adminConsoleServices:
- data
cluster:
dataServiceMemoryQuota: 256
indexServiceMemoryQuota: 256
searchServiceMemoryQuota: 256
eventingServiceMemoryQuota: 256
analyticsServiceMemoryQuota: 1024
indexStorageSetting: memory_optimized
autoFailoverTimeout: 120
autoFailoverMaxCount: 3
autoFailoverOnDataDiskIssues: true
autoFailoverOnDataDiskIssuesTimePeriod: 120
autoFailoverServerGroup: false
YAML
}
```
See [User Guide](https://registry.terraform.io/providers/gavinbunney/kubectl/latest) for details on installation and all the provided data and resource types.
---
## Development Guide
If you wish to work on the provider, you'll first need [Go](http://www.golang.org) installed on your machine (version 1.12+ is *required*).
You'll also need to correctly setup a [GOPATH](http://golang.org/doc/code.html#GOPATH), as well as adding `$GOPATH/bin` to your `$PATH`.
To compile the provider, run `make build`. This will build the provider and put the provider binary in the `$GOPATH/bin` directory.
### Building The Provider
```sh
$ go get github.com/gavinbunney/terraform-provider-kubectl
```
Enter the provider directory and build the provider
```sh
$ cd $GOPATH/src/github.com/gavinbunney/terraform-provider-kubectl
$ make build
```
### Testing
In order to test the provider, you can simply run `make test`.
```sh
$ make test
```
The provider uses k3s to run integration tests. These tests look for any `*.tf` files in the `_examples` folder and run an `plan`, `apply`, `refresh` and `plan` loop over each file.
Inside each file the string `name-here` is replaced with a unique name during test execution. This is a simple string replace before the TF is applied to ensure that tests don't fail due to naming clashes.
Each scenario can be placed in a folder, to help others navigate and use the examples, and added to the [README.MD](./_examples/README.MD).
> Note: The test infrastructure doesn't support multi-file TF configurations so ensure your test scenario is in a single file.
In order to run the full suite of Acceptance tests, run `make testacc`.
*Note:* Acceptance tests create real resources, and often cost money to run.
```sh
$ make testacc
```
### Inspiration
Thanks to the original provider by [nabancard and lawrecncegripper](https://github.com/nabancard/terraform-provider-kubernetes-yaml) on the original base of this provider.
terraform {
required_version = ">= 1.0"
required_providers {
helm = {
source = "hashicorp/helm"
version = "2.11.0"
}
kubectl = {
source = "gavinbunney/kubectl"
version = "1.14.0"
}
}
}
provider "helm" {
kubernetes {
config_path = "~/.kube/config"
}
}
provider "kubectl" {
config_path = "~/.kube/config"
}
# Install manually
# helm repo add grafana https://grafana.github.io/helm-charts
# helm repo update
# helm install tempo --namespace monitoring --create-namespace --version 1.6.2 --values terraform/values/tempo.yaml grafana/tempo
resource "helm_release" "tempo" {
name = "tempo"
repository = "https://grafana.github.io/helm-charts"
chart = "tempo"
namespace = "monitoring"
version = "1.6.2"
create_namespace = true
values = [file("values/tempo.yaml")]
}
# Install manually
# helm repo add grafana https://grafana.github.io/helm-charts
# helm repo update
# helm install grafana --namespace monitoring --create-namespace --version 6.60.6 --values terraform/values/grafana.yaml grafana/grafana
resource "helm_release" "grafana" {
name = "grafana"
repository = "https://grafana.github.io/helm-charts"
chart = "grafana"
namespace = "monitoring"
version = "6.60.6"
create_namespace = true
values = [file("values/grafana.yaml")]
}
{
"version": 4,
"terraform_version": "1.8.2",
"serial": 3,
"lineage": "290c0732-2779-c219-f7a0-9dba058af07a",
"outputs": {},
"resources": [
{
"mode": "managed",
"type": "helm_release",
"name": "grafana",
"provider": "provider[\"registry.terraform.io/hashicorp/helm\"]",
"instances": [
{
"schema_version": 1,
"attributes": {
"atomic": false,
"chart": "grafana",
"cleanup_on_fail": false,
"create_namespace": true,
"dependency_update": false,
"description": null,
"devel": null,
"disable_crd_hooks": false,
"disable_openapi_validation": false,
"disable_webhooks": false,
"force_update": false,
"id": "grafana",
"keyring": null,
"lint": false,
"manifest": null,
"max_history": 0,
"metadata": [
{
"app_version": "10.1.5",
"chart": "grafana",
"name": "grafana",
"namespace": "monitoring",
"revision": 1,
"values": "{\"adminPassword\":\"devops123\",\"adminUser\":\"admin\"}",
"version": "6.60.6"
}
],
"name": "grafana",
"namespace": "monitoring",
"pass_credentials": false,
"postrender": [],
"recreate_pods": false,
"render_subchart_notes": true,
"replace": false,
"repository": "https://grafana.github.io/helm-charts",
"repository_ca_file": null,
"repository_cert_file": null,
"repository_key_file": null,
"repository_password": null,
"repository_username": null,
"reset_values": false,
"reuse_values": false,
"set": [],
"set_list": [],
"set_sensitive": [],
"skip_crds": false,
"status": "deployed",
"timeout": 300,
"values": [
"---\nadminUser: admin\nadminPassword: devops123\n"
],
"verify": false,
"version": "6.60.6",
"wait": true,
"wait_for_jobs": false
},
"sensitive_attributes": [
[
{
"type": "get_attr",
"value": "repository_password"
}
]
],
"private": "eyJzY2hlbWFfdmVyc2lvbiI6IjEifQ=="
}
]
},
{
"mode": "managed",
"type": "helm_release",
"name": "tempo",
"provider": "provider[\"registry.terraform.io/hashicorp/helm\"]",
"instances": [
{
"schema_version": 1,
"attributes": {
"atomic": false,
"chart": "tempo",
"cleanup_on_fail": false,
"create_namespace": true,
"dependency_update": false,
"description": null,
"devel": null,
"disable_crd_hooks": false,
"disable_openapi_validation": false,
"disable_webhooks": false,
"force_update": false,
"id": "tempo",
"keyring": null,
"lint": false,
"manifest": null,
"max_history": 0,
"metadata": [
{
"app_version": "2.2.3",
"chart": "tempo",
"name": "tempo",
"namespace": "monitoring",
"revision": 1,
"values": "{\"datasources\":{\"datasources.yaml\":{\"apiVersion\":1,\"datasources\":[{\"access\":\"proxy\",\"apiVersion\":1,\"basicAuth\":false,\"editable\":false,\"isDefault\":true,\"name\":\"Tempo\",\"orgId\":1,\"type\":\"tempo\",\"uid\":\"tempo\",\"url\":\"http://tempo:3100\",\"version\":1}]}},\"env\":{\"GF_AUTH_ANONYMOUS_ENABLED\":true,\"GF_AUTH_ANONYMOUS_ORG_ROLE\":\"Admin\",\"GF_AUTH_DISABLE_LOGIN_FORM\":true}}",
"version": "1.6.2"
}
],
"name": "tempo",
"namespace": "monitoring",
"pass_credentials": false,
"postrender": [],
"recreate_pods": false,
"render_subchart_notes": true,
"replace": false,
"repository": "https://grafana.github.io/helm-charts",
"repository_ca_file": null,
"repository_cert_file": null,
"repository_key_file": null,
"repository_password": null,
"repository_username": null,
"reset_values": false,
"reuse_values": false,
"set": [],
"set_list": [],
"set_sensitive": [],
"skip_crds": false,
"status": "deployed",
"timeout": 300,
"values": [
"---\nenv:\n GF_AUTH_ANONYMOUS_ENABLED: true\n GF_AUTH_ANONYMOUS_ORG_ROLE: \"Admin\"\n GF_AUTH_DISABLE_LOGIN_FORM: true\n\ndatasources:\n datasources.yaml:\n apiVersion: 1\n\n datasources:\n - name: Tempo\n type: tempo\n access: proxy\n orgId: 1\n url: http://tempo:3100\n basicAuth: false\n isDefault: true\n version: 1\n editable: false\n apiVersion: 1\n uid: tempo\n"
],
"verify": false,
"version": "1.6.2",
"wait": true,
"wait_for_jobs": false
},
"sensitive_attributes": [
[
{
"type": "get_attr",
"value": "repository_password"
}
]
],
"private": "eyJzY2hlbWFfdmVyc2lvbiI6IjEifQ=="
}
]
}
],
"check_results": null
}
---
adminUser: admin
adminPassword: devops123
---
env:
GF_AUTH_ANONYMOUS_ENABLED: true
GF_AUTH_ANONYMOUS_ORG_ROLE: "Admin"
GF_AUTH_DISABLE_LOGIN_FORM: true
datasources:
datasources.yaml:
apiVersion: 1
datasources:
- name: Tempo
type: tempo
access: proxy
orgId: 1
url: http://tempo:3100
basicAuth: false
isDefault: true
version: 1
editable: false
apiVersion: 1
uid: tempo
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment