Skip to content

Commit

Permalink
Move service hash logic to Service.Hash method
Browse files Browse the repository at this point in the history
  • Loading branch information
schmichael committed Dec 8, 2017
1 parent 65bfbe5 commit afd5bca
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
15 changes: 1 addition & 14 deletions command/agent/consul/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -1023,20 +1023,7 @@ func makeAgentServiceID(role string, service *structs.Service) string {
//
// Example Service ID: _nomad-task-TNM333JKJPM5AK4FAS3VXQLXFDWOF4VH
func makeTaskServiceID(allocID, taskName string, service *structs.Service) string {
h := sha1.New()
io.WriteString(h, allocID)
io.WriteString(h, taskName)
io.WriteString(h, service.Name)
io.WriteString(h, service.PortLabel)
io.WriteString(h, service.AddressMode)
for _, tag := range service.Tags {
io.WriteString(h, tag)
}

// Base32 is used for encoding the hash as sha1 hashes can always be
// encoded without padding, only 4 bytes larger than base64, and saves
// 8 bytes vs hex.
return nomadTaskPrefix + base32.StdEncoding.EncodeToString(h.Sum(nil))
return nomadTaskPrefix + service.Hash(allocID, taskName)
}

// makeCheckID creates a unique ID for a check.
Expand Down
21 changes: 21 additions & 0 deletions nomad/structs/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/base32"
"encoding/hex"
"errors"
"fmt"
Expand Down Expand Up @@ -3140,6 +3141,26 @@ func (s *Service) ValidateName(name string) error {
return nil
}

// Hash returns a base32 encoded hash of a Service's contents excluding checks
// as they're hashed independently.
func (s *Service) Hash(allocID, taskName string) string {
h := sha1.New()
io.WriteString(h, allocID)
io.WriteString(h, taskName)
io.WriteString(h, s.Name)
io.WriteString(h, s.PortLabel)
io.WriteString(h, s.AddressMode)
for _, tag := range s.Tags {
io.WriteString(h, tag)
}

// Base32 is used for encoding the hash as sha1 hashes can always be
// encoded without padding, only 4 bytes larger than base64, and saves
// 8 bytes vs hex. Since these hashes are used in Consul URLs it's nice
// to have a reasonably compact URL-safe representation.
return base32.StdEncoding.EncodeToString(h.Sum(nil))
}

const (
// DefaultKillTimeout is the default timeout between signaling a task it
// will be killed and killing it.
Expand Down

0 comments on commit afd5bca

Please sign in to comment.