8000 feat: Add support for update checks and notifications by mafredri · Pull Request #4810 · coder/coder · GitHub
[go: up one dir, main page]

Skip to content

feat: Add support for update checks and notifications #4810

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 14 commits into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat: Add support for checking for updates
  • Loading branch information
mafredri committed Nov 29, 2022
commit cc28c1bab164b62c7720f30e1044a54d57b1249a
5 changes: 5 additions & 0 deletions buildinfo/buildinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ func VersionsMatch(v1, v2 string) bool {
return semver.MajorMinor(v1) == semver.MajorMinor(v2)
}

// IsDev returns true if this is a development build.
func IsDev() bool {
return strings.HasPrefix(Version(), develPrefix)
}

// ExternalURL returns a URL referencing the current Coder version.
// For production builds, this will link directly to a release.
// For development builds, this will link to a commit.
Expand Down
7 changes: 7 additions & 0 deletions cli/deployment/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/spf13/viper"
"golang.org/x/xerrors"

"github.com/coder/coder/buildinfo"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/cli/config"
"github.com/coder/coder/codersdk"
Expand Down Expand Up @@ -405,6 +406,12 @@ func newConfig() *codersdk.DeploymentConfig {
Usage: "Enable experimental features. Experimental features are not ready for production.",
Flag: "experimental",
},
UpdateCheck: &codersdk.DeploymentConfigField[bool]{
Name: "Update Check",
Usage: "Periodically check for new releases of Coder and inform the owner.",
Flag: "update-check",
Default: flag.Lookup("test.v") == nil && !buildinfo.IsDev(),
},
}
}

Expand Down
2 changes: 2 additions & 0 deletions cli/deployment/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func TestConfig(t *testing.T) {
"CODER_TELEMETRY": "false",
"CODER_TELEMETRY_TRACE": "false",
"CODER_WILDCARD_ACCESS_URL": "something-wildcard.com",
"CODER_UPDATE_CHECK": "false",
},
Valid: func(config *codersdk.DeploymentConfig) {
require.Equal(t, config.Address.Value, "0.0.0.0:8443")
Expand All @@ -53,6 +54,7 @@ func TestConfig(t *testing.T) {
require.Equal(t, config.Telemetry.Enable.Value, false)
require.Equal(t, config.Telemetry.Trace.Value, false)
require.Equal(t, config.WildcardAccessURL.Value, "something-wildcard.com")
require.Equal(t, config.UpdateCheck.Value, false)
},
}, {
Name: "DERP",
Expand Down
20 changes: 20 additions & 0 deletions cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import (
"github.com/coder/coder/coderd/prometheusmetrics"
"github.com/coder/coder/coderd/telemetry"
"github.com/coder/coder/coderd/tracing"
"github.com/coder/coder/coderd/updatecheck"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/cryptorand"
"github.com/coder/coder/provisioner/echo"
Expand Down Expand Up @@ -373,6 +374,25 @@ func Server(vip *viper.Viper, newAPI func(context.Context, *coderd.Options) (*co
options.TLSCertificates = tlsConfig.Certificates
}

if cfg.UpdateCheck.Value {
options.UpdateCheckOptions = &updatecheck.Options{
// Avoid spamming GitHub API checking for updates.
Interval: 24 * time.Hour,
// Inform server admins of new versions.
Notify: func(r updatecheck.Result) {
if semver.Compare(r.Version, buildinfo.Version()) > 0 {
options.Logger.Info(
context.Background(),
"new version of coder available",
slog.F("new_version", r.Version),
slog.F("url", r.URL),
slog.F("upgrade_instructions", "https://coder.com/docs/coder-oss/latest/admin/upgrade"),
)
}
},
}
}

if cfg.OAuth2.Github.ClientSecret.Value != "" {
options.GithubOAuth2Config, err = configureGithubOAuth2(accessURLParsed,
cfg.OAuth2.Github.ClientID.Value,
Expand Down
28 changes: 19 additions & 9 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import (
"github.com/coder/coder/coderd/rbac"
"github.com/coder/coder/coderd/telemetry"
"github.com/coder/coder/coderd/tracing"
"github.com/coder/coder/coderd/updatecheck"
"github.com/coder/coder/coderd/wsconncache"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/provisionerd/proto"
Expand Down Expand Up @@ -105,6 +106,7 @@ type Options struct {
AgentStatsRefreshInterval time.Duration
Experimental bool
DeploymentConfig *codersdk.DeploymentConfig
UpdateCheckOptions *updatecheck.Options // Set non-nil to enable update checking.
}

// New constructs a Coder API handler.
Expand All @@ -123,20 +125,14 @@ func New(options *Options) *API {
options.AgentInactiveDisconnectTimeout = options.AgentConnectionUpdateFrequency * 2
}
if options.AgentStatsRefreshInterval == 0 {
options.AgentStatsRefreshInterval = 10 * time.Minute
options.AgentStatsRefreshInterval = 5 * time.Minute
}
if options.MetricsCacheRefreshInterval == 0 {
options.MetricsCacheRefreshInterval = time.Hour
}
if options.APIRateLimit == 0 {
options.APIRateLimit = 512
}
if options.AgentStatsRefreshInterval == 0 {
options.AgentStatsRefreshInterval = 5 * time.Minute
}
if options.MetricsCacheRefreshInterval == 0 {
options.MetricsCacheRefreshInterval = time.Hour
}
if options.Authorizer == nil {
options.Authorizer = rbac.NewAuthorizer()
}
Expand Down Expand Up @@ -181,6 +177,13 @@ func New(options *Options) *API {
metricsCache: metricsCache,
Auditor: atomic.Pointer[audit.Auditor]{},
}
if options.UpdateCheckOptions != nil {
api.updateChecker = updatecheck.New(
options.Database,
options.Logger.Named("update_checker"),
*options.UpdateCheckOptions,
)
}
api.Auditor.Store(&options.Auditor)
api.workspaceAgentCache = wsconncache.New(api.dialWorkspaceAgentTailnet, 0)
api.TailnetCoordinator.Store(&options.TailnetCoordinator)
Expand Down Expand Up @@ -308,6 +311,9 @@ func New(options *Options) *API {
})
})
})
r.Route("/updatecheck", func(r chi.Router) {
r.Get("/", api.updateCheck)
})
r.Route("/config", func(r chi.Router) {
r.Use(apiKeyMiddleware)
r.Get("/deployment", api.deploymentConfig)
Expand Down Expand Up @@ -590,13 +596,14 @@ type API struct {
// RootHandler serves "/"
RootHandler chi.Router

metricsCache *metricscache.Cache
siteHandler http.Handler
siteHandler http.Handler

WebsocketWaitMutex sync.Mutex
WebsocketWaitGroup sync.WaitGroup

metricsCache *metricscache.Cache
workspaceAgentCache *wsconncache.Cache
updateChecker *updatecheck.Checker
}

// Close waits for all WebSocket connections to drain before returning.
Expand All @@ -606,6 +613,9 @@ func (api *API) Close() error {
api.WebsocketWaitMutex.Unlock()

api.metricsCache.Close()
if api.updateChecker != nil {
api.updateChecker.Close()
}
coordinator := api.TailnetCoordinator.Load()
if coordinator != nil {
_ = (*coordinator).Close()
Expand Down
5 changes: 5 additions & 0 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ import (
"github.com/coder/coder/coderd/httpmw"
"github.com/coder/coder/coderd/rbac"
"github.com/coder/coder/coderd/telemetry"
"github.com/coder/coder/coderd/updatecheck"
"github.com/coder/coder/coderd/util/ptr"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/cryptorand"
Expand Down Expand Up @@ -102,6 +103,9 @@ type Options struct {
AgentStatsRefreshInterval time.Duration
DeploymentConfig *codersdk.DeploymentConfig

// Set update check options to enable update check.
UpdateCheckOptions *updatecheck.Options

// Overriding the database is heavily discouraged.
// It should only be used in cases where multiple Coder
// test instances are running against the same database.
Expand Down Expand Up @@ -283,6 +287,7 @@ func NewOptions(t *testing.T, options *Options) (func(http.Handler), context.Can
MetricsCacheRefreshInterval: options.MetricsCacheRefreshInterval,
AgentStatsRefreshInterval: options.AgentStatsRefreshInterval,
DeploymentConfig: options.DeploymentConfig,
UpdateCheckOptions: options.UpdateCheckOptions,
}
}

Expand Down
25 changes: 22 additions & 3 deletions 8000 coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,10 @@ type data struct {
workspaceResources []database.WorkspaceResource
workspaces []database.Workspace

deploymentID string
derpMeshKey string
lastLicenseID int32
deploymentID string
derpMeshKey string
lastUpdateCheck []byte
lastLicenseID int32
}

func (fakeQuerier) IsFakeDB() {}
Expand Down Expand Up @@ -3272,6 +3273,24 @@ func (q *fakeQuerier) GetDERPMeshKey(_ context.Context) (string, error) {
return q.derpMeshKey, nil
}

func (q *fakeQuerier) InsertOrUpdateLastUpdateCheck(_ context.Context, data string) error {
q.mutex.RLock()
defer q.mutex.RUnlock()

q.lastUpdateCheck = []byte(data)
return nil
}

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

if q.lastUpdateCheck == nil {
return "", sql.ErrNoRows
}
return string(q.lastUpdateCheck), nil
}

func (q *fakeQuerier) InsertLicense(
_ context.Context, arg database.InsertLicenseParams,
) (database.License, error) {
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.

21 changes: 21 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.

7 changes: 7 additions & 0 deletions coderd/database/queries/siteconfig.sql
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,10 @@ INSERT INTO site_configs (key, value) VALUES ('derp_mesh_key', $1);

-- name: GetDERPMeshKey :one
SELECT value FROM site_configs WHERE key = 'derp_mesh_key';

-- name: InsertOrUpdateLastUpdateCheck :exec
INSERT INTO site_configs (key, value) VALUES ('last_update_check', $1)
ON CONFLICT (key) DO UPDATE SET value = $1 WHERE site_configs.key = 'last_update_check';

-- name: GetLastUpdateCheck :one
SELECT value FROM site_configs WHERE key = 'last_update_check';
38 changes: 38 additions & 0 deletions coderd/updatecheck.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package coderd

import (
"net/http"

"golang.org/x/mod/semver"

"github.com/coder/coder/buildinfo"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/codersdk"
)

func (api *API) updateCheck(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()

if api.updateChecker == nil {
// If update checking is disabled, echo the current
// version.
httpapi.Write(ctx, rw, http.StatusOK, codersdk.UpdateCheckResponse{
Current: true,
Version: buildinfo.Version(),
URL: buildinfo.ExternalURL(),
})
return
}

uc, err := api.updateChecker.Latest(ctx)
if err != nil {
httpapi.InternalServerError(rw, err)
return
}

httpapi.Write(ctx, rw, http.StatusOK, codersdk.UpdateCheckResponse{
Current: semver.Compare(buildinfo.Version(), uc.Version) >= 0,
Version: uc.Version,
URL: uc.URL,
})
}
Loading
0