Skip to content
This repository was archived by the owner on Nov 1, 2022. It is now read-only.

Commit

Permalink
Convert flux.ServiceID to a struct
Browse files Browse the repository at this point in the history
  • Loading branch information
awh committed Sep 5, 2017
1 parent b08d2a5 commit c45b65d
Show file tree
Hide file tree
Showing 24 changed files with 137 additions and 93 deletions.
2 changes: 1 addition & 1 deletion cluster/kubernetes/resource/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func (o Service) ServiceIDs(all map[string]resource.Resource) []flux.ServiceID {
if ns == "" {
ns = "default"
}
return []flux.ServiceID{flux.ServiceID(fmt.Sprintf("%s/%s", ns, o.Meta.Name))}
return []flux.ServiceID{flux.MustParseServiceID(fmt.Sprintf("%s/%s", ns, o.Meta.Name))}
}

// Matches checks if this service's label selectors match the labels fo some
Expand Down
6 changes: 3 additions & 3 deletions cluster/kubernetes/testfiles/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ func WriteTestFiles(dir string) error {
// given in the test data.
func ServiceMap(dir string) map[flux.ServiceID][]string {
return map[flux.ServiceID][]string{
flux.ServiceID("default/helloworld"): []string{filepath.Join(dir, "helloworld-deploy.yaml")},
flux.ServiceID("default/locked-service"): []string{filepath.Join(dir, "locked-service-deploy.yaml")},
flux.ServiceID("default/test-service"): []string{filepath.Join(dir, "test-service-deploy.yaml")},
flux.MustParseServiceID("default/helloworld"): []string{filepath.Join(dir, "helloworld-deploy.yaml")},
flux.MustParseServiceID("default/locked-service"): []string{filepath.Join(dir, "locked-service-deploy.yaml")},
flux.MustParseServiceID("default/test-service"): []string{filepath.Join(dir, "test-service-deploy.yaml")},
}
}

Expand Down
4 changes: 2 additions & 2 deletions cluster/manifests.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ type Manifests interface {
// UpdateManifest looks for the manifest for a given service, reads
// its contents, applies f(contents), and writes the results back to
// the file.
func UpdateManifest(m Manifests, root string, serviceID string, f func(manifest []byte) ([]byte, error)) error {
func UpdateManifest(m Manifests, root string, serviceID flux.ServiceID, f func(manifest []byte) ([]byte, error)) error {
services, err := m.FindDefinedServices(root)
if err != nil {
return err
}
paths := services[flux.ServiceID(serviceID)]
paths := services[serviceID]
if len(paths) == 0 {
return ErrNoResourceFilesFoundForService
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/fluxctl/list_images_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (opts *serviceShowOpts) RunE(cmd *cobra.Command, args []string) error {
continue
}

serviceName := service.ID
serviceName := service.ID.String()
var lineCount int
for _, container := range service.Containers {
containerName := container.Name
Expand Down Expand Up @@ -114,7 +114,7 @@ func (s imageStatusByName) Len() int {
}

func (s imageStatusByName) Less(a, b int) bool {
return s[a].ID < s[b].ID
return s[a].ID.String() < s[b].ID.String()
}

func (s imageStatusByName) Swap(a, b int) {
Expand Down
2 changes: 1 addition & 1 deletion cmd/fluxctl/list_services_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func (s serviceStatusByName) Len() int {
}

func (s serviceStatusByName) Less(a, b int) bool {
return s[a].ID < s[b].ID
return s[a].ID.String() < s[b].ID.String()
}

func (s serviceStatusByName) Swap(a, b int) {
Expand Down
10 changes: 5 additions & 5 deletions cmd/fluxsvc/fluxsvc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func setup(t *testing.T) {
mockPlatform = &remote.MockPlatform{
ListServicesAnswer: []flux.ServiceStatus{
flux.ServiceStatus{
ID: flux.ServiceID(helloWorldSvc),
ID: flux.MustParseServiceID(helloWorldSvc),
Status: "ok",
Containers: []flux.Container{
flux.Container{
Expand All @@ -90,7 +90,7 @@ func setup(t *testing.T) {
},
ListImagesAnswer: []flux.ImageStatus{
flux.ImageStatus{
ID: flux.ServiceID(helloWorldSvc),
ID: flux.MustParseServiceID(helloWorldSvc),
Containers: []flux.Container{
flux.Container{
Name: "helloworld",
Expand All @@ -101,7 +101,7 @@ func setup(t *testing.T) {
},
},
flux.ImageStatus{
ID: flux.ServiceID("a/another"),
ID: flux.MustParseServiceID("a/another"),
Containers: []flux.Container{
flux.Container{
Name: "helloworld",
Expand Down Expand Up @@ -159,7 +159,7 @@ func TestFluxsvc_ListServices(t *testing.T) {
if len(svcs) != 2 {
t.Error("Expected there to be two services")
}
if svcs[0].ID != helloWorldSvc && svcs[1].ID != helloWorldSvc {
if svcs[0].ID.String() != helloWorldSvc && svcs[1].ID.String() != helloWorldSvc {
t.Errorf("Expected one of the services to be %q", helloWorldSvc)
}

Expand Down Expand Up @@ -277,7 +277,7 @@ func TestFluxsvc_History(t *testing.T) {
err := eventLogger.LogEvent("", history.Event{
Type: history.EventLock,
ServiceIDs: []flux.ServiceID{
helloWorldSvc,
flux.MustParseServiceID(helloWorldSvc),
},
Message: "default/helloworld locked.",
})
Expand Down
2 changes: 1 addition & 1 deletion daemon/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ func (d *Daemon) updatePolicy(spec update.Spec, updates policy.Updates) DaemonJo
anythingAutomated = true
}
// find the service manifest
err := cluster.UpdateManifest(d.Manifests, working.ManifestDir(), string(serviceID), func(def []byte) ([]byte, error) {
err := cluster.UpdateManifest(d.Manifests, working.ManifestDir(), serviceID, func(def []byte) ([]byte, error) {
newDef, err := d.Manifests.UpdatePolicies(def, u)
if err != nil {
metadata.Result[serviceID] = update.ServiceResult{
Expand Down
4 changes: 2 additions & 2 deletions daemon/daemon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ func mockDaemon(t *testing.T) (*Daemon, func(), *cluster.Mock, history.EventRead
logger := log.NewNopLogger()

singleService := cluster.Service{
ID: flux.ServiceID(svc),
ID: flux.MustParseServiceID(svc),
Containers: cluster.ContainersOrExcuse{
Containers: []cluster.Container{
{
Expand Down Expand Up @@ -493,7 +493,7 @@ func updatePolicy(t *testing.T, d *Daemon) job.ID {
return updateManifest(t, d, update.Spec{
Type: update.Policy,
Spec: policy.Updates{
"default/helloworld": {
flux.MustParseServiceID("default/helloworld"): {
Add: policy.Set{
policy.Locked: "true",
},
Expand Down
21 changes: 15 additions & 6 deletions daemon/loop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ func TestPullAndSync_InitialSync(t *testing.T) {

syncCalled := 0
var syncDef *cluster.SyncDef
expectedServiceIDs := flux.ServiceIDs{"default/locked-service", "default/test-service", "default/helloworld"}
expectedServiceIDs := flux.ServiceIDs{
flux.MustParseServiceID("default/locked-service"),
flux.MustParseServiceID("default/test-service"),
flux.MustParseServiceID("default/helloworld")}
expectedServiceIDs.Sort()
k8s.SyncFunc = func(def cluster.SyncDef) error {
syncCalled++
Expand Down Expand Up @@ -145,7 +148,10 @@ func TestDoSync_NoNewCommits(t *testing.T) {

syncCalled := 0
var syncDef *cluster.SyncDef
expectedServiceIDs := flux.ServiceIDs{"default/locked-service", "default/test-service", "default/helloworld"}
expectedServiceIDs := flux.ServiceIDs{
flux.MustParseServiceID("default/locked-service"),
flux.MustParseServiceID("default/test-service"),
flux.MustParseServiceID("default/helloworld")}
expectedServiceIDs.Sort()
k8s.SyncFunc = func(def cluster.SyncDef) error {
syncCalled++
Expand Down Expand Up @@ -200,7 +206,7 @@ func TestDoSync_WithNewCommit(t *testing.T) {
t.Fatal(err)
}
// Push some new changes
if err := cluster.UpdateManifest(k8s, d.Checkout.ManifestDir(), "default/helloworld", func(def []byte) ([]byte, error) {
if err := cluster.UpdateManifest(k8s, d.Checkout.ManifestDir(), flux.MustParseServiceID("default/helloworld"), func(def []byte) ([]byte, error) {
// A simple modification so we have changes to push
return []byte(strings.Replace(string(def), "replicas: 5", "replicas: 4", -1)), nil
}); err != nil {
Expand All @@ -216,7 +222,10 @@ func TestDoSync_WithNewCommit(t *testing.T) {

syncCalled := 0
var syncDef *cluster.SyncDef
expectedServiceIDs := flux.ServiceIDs{"default/locked-service", "default/test-service", "default/helloworld"}
expectedServiceIDs := flux.ServiceIDs{
flux.MustParseServiceID("default/locked-service"),
flux.MustParseServiceID("default/test-service"),
flux.MustParseServiceID("default/helloworld")}
expectedServiceIDs.Sort()
k8s.SyncFunc = func(def cluster.SyncDef) error {
syncCalled++
Expand Down Expand Up @@ -248,8 +257,8 @@ func TestDoSync_WithNewCommit(t *testing.T) {
gotServiceIDs := es[0].ServiceIDs
flux.ServiceIDs(gotServiceIDs).Sort()
// Event should only have changed service ids
if !reflect.DeepEqual(gotServiceIDs, []flux.ServiceID{"default/helloworld"}) {
t.Errorf("Unexpected event service ids: %#v, expected: %#v", gotServiceIDs, []flux.ServiceID{"default/helloworld"})
if !reflect.DeepEqual(gotServiceIDs, []flux.ServiceID{flux.MustParseServiceID("default/helloworld")}) {
t.Errorf("Unexpected event service ids: %#v, expected: %#v", gotServiceIDs, []flux.ServiceID{flux.MustParseServiceID("default/helloworld")})
}
}
// It moves the tag
Expand Down
56 changes: 45 additions & 11 deletions flux.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package flux

import (
"encoding/json"
"fmt"
"net/http"
"sort"
Expand All @@ -25,38 +26,71 @@ func (t Token) Set(req *http.Request) {

// (User) Service identifiers

type ServiceID string // "default/helloworld"
type ServiceID struct {
namespace string
service string
}

func (id ServiceID) String() string {
return string(id)
return fmt.Sprintf("%s/%s", id.namespace, id.service)
}

func ParseServiceID(s string) (ServiceID, error) {
toks := strings.SplitN(s, "/", 2)
if len(toks) != 2 {
return "", errors.Wrap(ErrInvalidServiceID, "parsing "+s)
return ServiceID{}, errors.Wrap(ErrInvalidServiceID, "parsing "+s)
}
return ServiceID{toks[0], toks[1]}, nil
}

func MustParseServiceID(s string) ServiceID {
id, err := ParseServiceID(s)
if err != nil {
panic(err)
}
return ServiceID(s), nil
return id
}

func MakeServiceID(namespace, service string) ServiceID {
return ServiceID(namespace + "/" + service)
return ServiceID{namespace, service}
}

func (id ServiceID) Components() (namespace, service string) {
toks := strings.SplitN(string(id), "/", 2)
if len(toks) != 2 {
panic("invalid service spec")
return id.namespace, id.service
}

func (id ServiceID) MarshalJSON() ([]byte, error) {
return json.Marshal(id.String())
}

func (id *ServiceID) UnmarshalJSON(data []byte) (err error) {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
*id, err = ParseServiceID(string(str))
return err
}

func (id ServiceID) MarshalText() (text []byte, err error) {
return []byte(id.String()), nil
}

func (id *ServiceID) UnmarshalText(text []byte) error {
result, err := ParseServiceID(string(text))
if err != nil {
return err
}
return toks[0], toks[1]
*id = result
return nil
}

type ServiceIDSet map[ServiceID]struct{}

func (s ServiceIDSet) String() string {
var ids []string
for id := range s {
ids = append(ids, string(id))
ids = append(ids, id.String())
}
return "{" + strings.Join(ids, ", ") + "}"
}
Expand Down Expand Up @@ -117,7 +151,7 @@ func (s ServiceIDSet) ToSlice() ServiceIDs {
type ServiceIDs []ServiceID

func (p ServiceIDs) Len() int { return len(p) }
func (p ServiceIDs) Less(i, j int) bool { return string(p[i]) < string(p[j]) }
func (p ServiceIDs) Less(i, j int) bool { return p[i].String() < p[j].String() }
func (p ServiceIDs) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p ServiceIDs) Sort() { sort.Sort(p) }

Expand Down
2 changes: 1 addition & 1 deletion git/gittest/repo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func TestCheckout(t *testing.T) {
Spec: update.ReleaseSpec{},
},
Result: update.Result{
flux.ServiceID("service1"): update.ServiceResult{
flux.MustParseServiceID("default/service1"): update.ServiceResult{
Status: update.ReleaseStatusFailed,
Error: "failed the frobulator",
},
Expand Down
2 changes: 1 addition & 1 deletion history/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ type Event struct {
func (e Event) ServiceIDStrings() []string {
var strServiceIDs []string
for _, serviceID := range e.ServiceIDs {
strServiceIDs = append(strServiceIDs, string(serviceID))
strServiceIDs = append(strServiceIDs, serviceID.String())
}
sort.Strings(strServiceIDs)
return strServiceIDs
Expand Down
6 changes: 3 additions & 3 deletions history/sql/pg.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func (db *pgDB) scanEvents(query squirrel.Sqlizer) ([]history.Event, error) {
return nil, err
}
for _, id := range serviceIDs {
h.ServiceIDs = append(h.ServiceIDs, flux.ServiceID(id))
h.ServiceIDs = append(h.ServiceIDs, flux.MustParseServiceID(id))
}

if len(metadataBytes) > 0 {
Expand Down Expand Up @@ -94,7 +94,7 @@ func (db *pgDB) scanEvents(query squirrel.Sqlizer) ([]history.Event, error) {
func (db *pgDB) EventsForService(inst service.InstanceID, service flux.ServiceID, before time.Time, limit int64, after time.Time) ([]history.Event, error) {
q := db.eventsQuery().
Where("instance_id = ?", string(inst)).
Where("service_ids @> ?", pq.StringArray{string(service)}).
Where("service_ids @> ?", pq.StringArray{service.String()}).
Where("started_at < ?", before).
Where("started_at > ?", after)
if limit >= 0 {
Expand Down Expand Up @@ -136,7 +136,7 @@ func (db *pgDB) LogEvent(inst service.InstanceID, e history.Event) error {
}
serviceIDs := pq.StringArray{}
for _, id := range e.ServiceIDs {
serviceIDs = append(serviceIDs, string(id))
serviceIDs = append(serviceIDs, id.String())
}
_, err = db.driver.Exec(
`INSERT INTO events
Expand Down
6 changes: 3 additions & 3 deletions history/sql/ql.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func (db *qlDB) scanEvents(query squirrel.Sqlizer) ([]history.Event, error) {
func (db *qlDB) EventsForService(inst service.InstanceID, service flux.ServiceID, before time.Time, limit int64, after time.Time) ([]history.Event, error) {
q := db.eventsQuery().
Where("instance_id = ?", string(inst)).
Where("id(e) IN (select event_id from event_service_ids WHERE service_id = ?)", string(service)).
Where("id(e) IN (select event_id from event_service_ids WHERE service_id = ?)", service.String()).
Where("started_at < ?", before).
Where("started_at > ?", after)
if limit >= 0 {
Expand Down Expand Up @@ -139,7 +139,7 @@ func (db *qlDB) loadServiceIDs(events []history.Event) ([]history.Event, error)
if err := rows.Scan(&id); err != nil {
return nil, err
}
e.ServiceIDs = append(e.ServiceIDs, flux.ServiceID(id))
e.ServiceIDs = append(e.ServiceIDs, flux.MustParseServiceID(id))
}
if err := rows.Err(); err != nil {
return nil, err
Expand Down Expand Up @@ -193,7 +193,7 @@ func (db *qlDB) LogEvent(inst service.InstanceID, e history.Event) (err error) {
`INSERT INTO event_service_ids
(event_id, service_id)
VALUES ($1, $2)`,
id, string(serviceID),
id, serviceID.String(),
)
if err != nil {
return err
Expand Down
8 changes: 4 additions & 4 deletions history/sql/sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,22 @@ func TestHistoryLog(t *testing.T) {
defer db.Close()

bailIfErr(t, db.LogEvent(instance, history.Event{
ServiceIDs: []flux.ServiceID{flux.ServiceID("namespace/service")},
ServiceIDs: []flux.ServiceID{flux.MustParseServiceID("namespace/service")},
Type: "test",
Message: "event 1",
}))
bailIfErr(t, db.LogEvent(instance, history.Event{
ServiceIDs: []flux.ServiceID{flux.ServiceID("namespace/other")},
ServiceIDs: []flux.ServiceID{flux.MustParseServiceID("namespace/other")},
Type: "test",
Message: "event 3",
}))
bailIfErr(t, db.LogEvent(instance, history.Event{
ServiceIDs: []flux.ServiceID{flux.ServiceID("namespace/service")},
ServiceIDs: []flux.ServiceID{flux.MustParseServiceID("namespace/service")},
Type: "test",
Message: "event 2",
}))

es, err := db.EventsForService(instance, flux.ServiceID("namespace/service"), time.Now().UTC(), -1, time.Unix(0, 0))
es, err := db.EventsForService(instance, flux.MustParseServiceID("namespace/service"), time.Now().UTC(), -1, time.Unix(0, 0))
if err != nil {
t.Fatal(err)
}
Expand Down
2 changes: 1 addition & 1 deletion http/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (c *Client) UpdateImages(_ service.InstanceID, s update.ReleaseSpec, cause
args = append(args, "service", string(spec))
}
for _, ex := range s.Excludes {
args = append(args, "exclude", string(ex))
args = append(args, "exclude", ex.String())
}
if cause.Message != "" {
args = append(args, "message", cause.Message)
Expand Down
Loading

0 comments on commit c45b65d

Please sign in to comment.