Skip to content

Use licenses to populate the Entitlements API #3715

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

Merged
merged 7 commits into from
Aug 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions cli/features.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"bytes"
"encoding/json"
"fmt"
"strings"
Expand Down Expand Up @@ -53,12 +54,14 @@ func featuresList() *cobra.Command {
return xerrors.Errorf("render table: %w", err)
}
case "json":
outBytes, err := json.Marshal(entitlements)
buf := new(bytes.Buffer)
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
err = enc.Encode(entitlements)
if err != nil {
return xerrors.Errorf("marshal features to JSON: %w", err)
}

out = string(outBytes)
out = buf.String()
default:
return xerrors.Errorf(`unknown output format %q, only "table" and "json" are supported`, outputFormat)
}
Expand Down
6 changes: 5 additions & 1 deletion coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ type Options struct {
TracerProvider *sdktrace.TracerProvider
AutoImportTemplates []AutoImportTemplate
LicenseHandler http.Handler
FeaturesService FeaturesService
}

// New constructs a Coder API handler.
Expand Down Expand Up @@ -97,6 +98,9 @@ func New(options *Options) *API {
if options.LicenseHandler == nil {
options.LicenseHandler = licenses()
}
if options.FeaturesService == nil {
options.FeaturesService = featuresService{}
}

siteCacheDir := options.CacheDir
if siteCacheDir != "" {
Expand Down Expand Up @@ -406,7 +410,7 @@ func New(options *Options) *API {
})
r.Route("/entitlements", func(r chi.Router) {
r.Use(apiKeyMiddleware)
r.Get("/", entitlements)
r.Get("/", api.FeaturesService.EntitlementsAPI)
})
r.Route("/licenses", func(r chi.Router) {
r.Use(apiKeyMiddleware)
Expand Down
28 changes: 28 additions & 0 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,19 @@ func (q *fakeQuerier) GetUserCount(_ context.Context) (int64, error) {
return int64(len(q.users)), nil
}

func (q *fakeQuerier) GetActiveUserCount(_ context.Context) (int64, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()

active := int64(0)
for _, u := range q.users {
if u.Status == database.UserStatusActive {
active++
}
}
return active, nil
}

func (q *fakeQuerier) GetUsers(_ context.Context, params database.GetUsersParams) ([]database.User, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()
Expand Down Expand Up @@ -2322,6 +2335,21 @@ func (q *fakeQuerier) GetLicenses(_ context.Context) ([]database.License, error)
return results, nil
}

func (q *fakeQuerier) GetUnexpiredLicenses(_ context.Context) ([]database.License, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()

now := time.Now()
var results []database.License
for _, l := range q.licenses {
if l.Exp.After(now) {
results = append(results, l)
}
}
sort.Slice(results, func(i, j int) bool { return results[i].ID < results[j].ID })
return results, nil
}

func (q *fakeQuerier) DeleteLicense(_ context.Context, id int32) (int32, error) {
q.mutex.Lock()
defer q.mutex.Unlock()
Expand Down
2 changes: 2 additions & 0 deletions coderd/database/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 51 additions & 0 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions coderd/database/queries/licenses.sql
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ SELECT *
FROM licenses
ORDER BY (id);

-- name: GetUnexpiredLicenses :many
SELECT *
FROM licenses
WHERE exp > NOW()
ORDER BY (id);

-- name: DeleteLicense :one
DELETE
FROM licenses
Expand Down
8 changes: 8 additions & 0 deletions coderd/database/queries/users.sql
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ SELECT
FROM
users;

-- name: GetActiveUserCount :one
SELECT
COUNT(*)
FROM
users
WHERE
status = 'active'::public.user_status;

-- name: InsertUser :one
INSERT INTO
users (
Expand Down
15 changes: 14 additions & 1 deletion coderd/features.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,20 @@ import (
"github.com/coder/coder/codersdk"
)

func entitlements(rw http.ResponseWriter, _ *http.Request) {
// FeaturesService is the interface for interacting with enterprise features.
type FeaturesService interface {
EntitlementsAPI(w http.ResponseWriter, r *http.Request)

// TODO
// Get returns the implementations for feature interfaces. Parameter `s `must be a pointer to a
// struct type containing feature interfaces as fields. The FeatureService sets all fields to
// the correct implementations depending on whether the features are turned on.
// Get(s any) error
}

type featuresService struct{}

func (featuresService) EntitlementsAPI(rw http.ResponseWriter, _ *http.Request) {
features := make(map[string]codersdk.Feature)
for _, f := range codersdk.FeatureNames {
features[f] = codersdk.Feature{
Expand Down
2 changes: 1 addition & 1 deletion coderd/features_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestEntitlements(t *testing.T) {
t.Parallel()
r := httptest.NewRequest("GET", "https://example.com/api/v2/entitlements", nil)
rw := httptest.NewRecorder()
entitlements(rw, r)
featuresService{}.EntitlementsAPI(rw, r)
resp := rw.Result()
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
Expand Down
4 changes: 2 additions & 2 deletions codersdk/features.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ var FeatureNames = []string{FeatureUserLimit, FeatureAuditLog}
type Feature struct {
Entitlement Entitlement `json:"entitlement"`
Enabled bool `json:"enabled"`
Limit *int64 `json:"limit"`
Actual *int64 `json:"actual"`
Limit *int64 `json:"limit,omitempty"`
Actual *int64 `json:"actual,omitempty"`
}

type Entitlements struct {
Expand Down
19 changes: 19 additions & 0 deletions enterprise/coderd/coderd.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
package coderd

import (
"context"
"os"
"strings"

"golang.org/x/xerrors"

"github.com/coder/coder/coderd"
"github.com/coder/coder/coderd/rbac"
)

const EnvAuditLogEnable = "CODER_AUDIT_LOG_ENABLE"

func NewEnterprise(options *coderd.Options) *coderd.API {
var eOpts = *options
if eOpts.Authorizer == nil {
Expand All @@ -26,5 +32,18 @@ func NewEnterprise(options *coderd.Options) *coderd.API {
Authorizer: eOpts.Authorizer,
Logger: eOpts.Logger,
}).handler()
en := Enablements{AuditLogs: true}
auditLog := os.Getenv(EnvAuditLogEnable)
auditLog = strings.ToLower(auditLog)
if auditLog == "disable" || auditLog == "false" || auditLog == "0" || auditLog == "no" {
en.AuditLogs = false
}
eOpts.FeaturesService = newFeaturesService(
context.Background(),
eOpts.Logger,
eOpts.Database,
eOpts.Pubsub,
en,
)
return coderd.New(&eOpts)
}
Loading