-
Notifications
You must be signed in to change notification settings - Fork 103
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
create http dispatcher #91
Open
patrickdemers6
wants to merge
1
commit into
main
Choose a base branch
from
http-producer
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,241 @@ | ||
package http | ||
|
||
import ( | ||
"bytes" | ||
"crypto/tls" | ||
"errors" | ||
"fmt" | ||
"hash/fnv" | ||
"net/http" | ||
"sync" | ||
"time" | ||
|
||
"github.com/sirupsen/logrus" | ||
|
||
"github.com/teslamotors/fleet-telemetry/metrics" | ||
"github.com/teslamotors/fleet-telemetry/metrics/adapter" | ||
"github.com/teslamotors/fleet-telemetry/telemetry" | ||
) | ||
|
||
const ( | ||
jsonContentType = "application/json" | ||
protobufContentType = "application/x-protobuf" | ||
) | ||
|
||
// Producer client to handle http | ||
type Producer struct { | ||
namespace string | ||
metricsCollector metrics.MetricCollector | ||
logger *logrus.Logger | ||
workerChannels []chan *telemetry.Record | ||
address string | ||
httpClient http.Client | ||
produceDecodedRecords bool | ||
} | ||
|
||
// Metrics stores metrics reported from this package | ||
type Metrics struct { | ||
produceCount adapter.Counter | ||
byteTotal adapter.Counter | ||
errorCount adapter.Counter | ||
bufferSize adapter.Gauge | ||
} | ||
|
||
// TLSCertificate contains the paths to the certificate and key files. | ||
type TLSCertificate struct { | ||
CertFile string `json:"cert"` | ||
KeyFile string `json:"key"` | ||
} | ||
|
||
// Config contains the data necessary to configure an http producer. | ||
type Config struct { | ||
// WorkerCount is the number of http producer routines running. | ||
// This number should be increased if `http_produce_buffer_size` is growing. | ||
// To guarantee message delivery order, messages from a specific vehicle are | ||
// always assigned to the same worker. Load among workers may not be evenly distributed. | ||
WorkerCount int `json:"worker_count"` | ||
|
||
// Address is the address to produce requests to. | ||
Address string `json:"address"` | ||
|
||
// Timeout is the number of seconds to wait for a response. Defaults to 10. | ||
Timeout int `json:"timeout"` | ||
|
||
// TLS is the TLS configuration for the http producer. | ||
TLS *TLSCertificate `json:"tls,omitempty"` | ||
} | ||
|
||
const ( | ||
statusCodePreSendErr = "NOT_SENT" | ||
bufferSize = 128 | ||
) | ||
|
||
var ( | ||
metricsRegistry Metrics | ||
metricsOnce sync.Once | ||
) | ||
|
||
// NewProducer sets up an HTTP producer | ||
func NewProducer(config *Config, produceDecodedRecords bool, metricsCollector metrics.MetricCollector, namespace string, logger *logrus.Logger) (telemetry.Producer, error) { | ||
registerMetricsOnce(metricsCollector) | ||
|
||
err := validateConfig(config) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
transport := http.DefaultTransport | ||
if config.TLS != nil { | ||
transport, err = getTransport(config.TLS) | ||
if err != nil { | ||
return nil, err | ||
} | ||
} | ||
|
||
producer := &Producer{ | ||
namespace: namespace, | ||
metricsCollector: metricsCollector, | ||
workerChannels: make([]chan *telemetry.Record, config.WorkerCount), | ||
address: config.Address, | ||
logger: logger, | ||
produceDecodedRecords: produceDecodedRecords, | ||
httpClient: http.Client{ | ||
Timeout: time.Duration(config.Timeout) * time.Second, | ||
Transport: transport, | ||
}, | ||
} | ||
|
||
for i := 0; i < config.WorkerCount; i++ { | ||
producer.workerChannels[i] = make(chan *telemetry.Record, bufferSize) | ||
go producer.worker(getWorkerId(i), producer.workerChannels[i]) | ||
} | ||
|
||
logger.Infof("registered http producer for namespace: %s", namespace) | ||
return producer, nil | ||
} | ||
|
||
// validateConfig validates configuration values and sets defaults if value not set | ||
func validateConfig(c *Config) error { | ||
if c.WorkerCount < 0 { | ||
return errors.New("invalid http worker count") | ||
} | ||
if c.WorkerCount == 0 { | ||
c.WorkerCount = 5 | ||
} | ||
if c.Timeout < 0 { | ||
return errors.New("invalid http timeout") | ||
} | ||
if c.Timeout == 0 { | ||
c.Timeout = 10 | ||
} | ||
return nil | ||
} | ||
|
||
func getTransport(tlsConfig *TLSCertificate) (*http.Transport, error) { | ||
clientTLSCert, err := tls.LoadX509KeyPair(tlsConfig.CertFile, tlsConfig.KeyFile) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return &http.Transport{ | ||
TLSClientConfig: &tls.Config{ | ||
Certificates: []tls.Certificate{clientTLSCert}, | ||
}, | ||
}, nil | ||
} | ||
|
||
func (p *Producer) worker(id string, records <-chan *telemetry.Record) { | ||
for record := range records { | ||
metricsRegistry.bufferSize.Sub(1, map[string]string{"worker": id}) | ||
p.sendHTTP(record) | ||
} | ||
} | ||
|
||
func getWorkerId(idx int) string { | ||
return fmt.Sprintf("worker-%d", idx) | ||
} | ||
|
||
func (p *Producer) sendHTTP(record *telemetry.Record) { | ||
url := fmt.Sprintf("%s?namespace=%s&type=%s", p.address, p.namespace, record.TxType) | ||
payload := record.Payload() | ||
|
||
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload)) | ||
if err != nil { | ||
p.logError(fmt.Errorf("create_request_err %s", err.Error())) | ||
return | ||
} | ||
|
||
contentType := protobufContentType | ||
if p.produceDecodedRecords { | ||
contentType = jsonContentType | ||
} | ||
req.Header.Set("Content-Type", contentType) | ||
for key, value := range record.Metadata() { | ||
req.Header.Set(key, value) | ||
} | ||
|
||
resp, err := p.httpClient.Do(req) | ||
if err != nil { | ||
p.logError(fmt.Errorf("send_request_err %s", err.Error())) | ||
return | ||
} | ||
defer resp.Body.Close() | ||
|
||
if resp.StatusCode >= 200 && resp.StatusCode <= 299 { | ||
metricsRegistry.produceCount.Inc(map[string]string{"record_type": record.TxType}) | ||
metricsRegistry.byteTotal.Add(int64(record.Length()), map[string]string{"record_type": record.TxType}) | ||
return | ||
} | ||
p.logError(fmt.Errorf("response_status_code %d", resp.StatusCode)) | ||
} | ||
|
||
func vinToHash(vin string) uint32 { | ||
h := fnv.New32a() | ||
h.Write([]byte(vin)) | ||
return h.Sum32() | ||
} | ||
|
||
func (p *Producer) getRecordChannelIndex(vin string) int { | ||
return int(vinToHash(vin) % uint32(len(p.workerChannels))) | ||
} | ||
|
||
// Produce asynchronously sends the record payload to http endpoint | ||
func (p *Producer) Produce(record *telemetry.Record) { | ||
idx := p.getRecordChannelIndex(record.Vin) | ||
p.workerChannels[idx] <- record | ||
metricsRegistry.bufferSize.Inc(map[string]string{"worker": getWorkerId(idx)}) | ||
} | ||
|
||
func (p *Producer) logError(err error) { | ||
p.logger.Errorf("http_producer_err err: %v", err) | ||
metricsRegistry.errorCount.Inc(map[string]string{}) | ||
} | ||
|
||
func registerMetricsOnce(metricsCollector metrics.MetricCollector) { | ||
metricsOnce.Do(func() { registerMetrics(metricsCollector) }) | ||
} | ||
|
||
func registerMetrics(metricsCollector metrics.MetricCollector) { | ||
metricsRegistry.produceCount = metricsCollector.RegisterCounter(adapter.CollectorOptions{ | ||
Name: "http_produce_total", | ||
Help: "The number of records produced to http.", | ||
Labels: []string{"record_type"}, | ||
}) | ||
|
||
metricsRegistry.byteTotal = metricsCollector.RegisterCounter(adapter.CollectorOptions{ | ||
Name: "http_produce_total_bytes", | ||
Help: "The number of bytes produced to http.", | ||
Labels: []string{"record_type"}, | ||
}) | ||
|
||
metricsRegistry.errorCount = metricsCollector.RegisterCounter(adapter.CollectorOptions{ | ||
Name: "http_produce_err", | ||
Help: "The number of errors while producing to http.", | ||
Labels: []string{}, | ||
}) | ||
|
||
metricsRegistry.bufferSize = metricsCollector.RegisterGauge(adapter.CollectorOptions{ | ||
Name: "http_produce_buffer_size", | ||
Help: "The number of records waiting to be produced per worker.", | ||
Labels: []string{"worker"}, | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package http_test | ||
|
||
import ( | ||
"testing" | ||
|
||
. "github.com/onsi/ginkgo/v2" | ||
. "github.com/onsi/gomega" | ||
) | ||
|
||
func TestConfigs(t *testing.T) { | ||
RegisterFailHandler(Fail) | ||
RunSpecs(t, "Http Producer Suite Tests") | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Updated to set
Content-Type
based on json vs protobuf. I'm usingapplication/x-protobuf
when it's the proto, but there are not clear standards on this available. Open to suggestion on this.