Skip to content

Commit

Permalink
Merge pull request #300 from clcollins/OSD-15847_osdctl_ocm_container
Browse files Browse the repository at this point in the history
Reorder bashrc.d by type; skip automation if launched without bin; fix env and login
openshift-merge-bot[bot] authored Aug 14, 2024
2 parents c3c32f0 + 2ec293e commit 2d9e91d
Showing 27 changed files with 194 additions and 339 deletions.
3 changes: 1 addition & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -113,8 +113,7 @@ tag-n-push: registry-login tag push

# Golang-related
.PHONY: go_build
go_build:
mod fmt lint test build_snapshot
go_build: mod fmt lint test build_snapshot

.PHONY: build_binary
build_binary:
5 changes: 2 additions & 3 deletions cmd/configure.go
Original file line number Diff line number Diff line change
@@ -37,9 +37,9 @@ const (
const (
sshDeprecationMsg = "SSH multiplexing and Socket mounting is no longer needed or supported. Please remove the 'DISABLE_SSH_MULTIPLEXING' and 'SSH_AUTH_SOCK' fields from your configuration."
backplaneConfigDirDeprecationMsg = "The 'BACKPLANE_CONFIG_DIR' field is deprecated and will be removed in a future version. Please remove it from your configuration. You may specify an alternate backplane config file with 'BACKPLANE_CONFIG'."
ocmUrlDeprecationMsg = "The 'OCM_URL' field is deprecated and will be removed in a future version. Please remove it from your configuration."
ocmUrlDeprecationMsg = "The 'OCM_URL' field is deprecated and no longer used. Please remove it from your configuration."
ocmUserDeprecationMsg = "The 'OCM_USER' field is deprecated and will be removed in a future version. Please remove it from your configuration."
ocmOatDeprecationMsg = "The 'OFFLINE_ACCESS_TOKEN' field is deprecated and will be removed in a future version. Please remove it from your configuration."
ocmOatDeprecationMsg = "The 'OFFLINE_ACCESS_TOKEN' field is deprecated no longer used. Please remove it from your configuration."
cliDeprecationMsg = "The 'CLI' field is deprecated and will be removed in a future version. Please remove it from your configuration."
)

@@ -60,7 +60,6 @@ var (
{"ca_source_anchors", false, optional},
{"engine", false, required},
{"jira_token", true, optional},
{"ocm_url", false, optional}, // Maybe - depends on the changes to ocm login
{"pagerduty_token", true, optional},
}

3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -5,6 +5,7 @@ go 1.22.1
require (
github.com/charmbracelet/bubbletea v0.25.0
github.com/charmbracelet/huh v0.3.1-0.20240306161957-71f31c155b08
github.com/openshift-online/ocm-cli v0.1.66
github.com/openshift-online/ocm-sdk-go v0.1.405
github.com/openshift/osdctl v0.28.0
github.com/sirupsen/logrus v1.9.3
@@ -69,6 +70,7 @@ require (
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/microcosm-cc/bluemonday v1.0.23 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
@@ -80,7 +82,6 @@ require (
github.com/muesli/termenv v0.15.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/nwidger/jsoncolor v0.3.2 // indirect
github.com/openshift-online/ocm-cli v0.1.66 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
github.com/pkg/errors v0.9.1 // indirect
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -196,6 +196,8 @@ github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zk
github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
github.com/microcosm-cc/bluemonday v1.0.23 h1:SMZe2IGa0NuHvnVNAZ+6B38gsTbi5e4sViiWJyDDqFY=
github.com/microcosm-cc/bluemonday v1.0.23/go.mod h1:mN70sk7UkkF8TUr2IGBpNN0jAgStuPzlK76QuruE/z4=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/moby/term v0.0.0-20221205130635-1aeaba878587 h1:HfkjXDfhgVaN5rmueG8cL8KKeFNecRCXFhaJ2qZ5SKA=
2 changes: 1 addition & 1 deletion pkg/engine/engine.go
Original file line number Diff line number Diff line change
@@ -243,7 +243,7 @@ func parseRefToArgs(c ContainerRef) ([]string, error) {
if c.PublishAll {
args = append(args, "--publish-all")
} else if c.LocalPorts != nil {
for service, _ := range c.LocalPorts {
for service := range c.LocalPorts {
args = append(args, fmt.Sprintf("--publish=127.0.0.1::%d", c.LocalPorts[service]))
}
}
154 changes: 120 additions & 34 deletions pkg/ocm/ocm.go
Original file line number Diff line number Diff line change
@@ -5,24 +5,35 @@ package ocm
// creating the container

import (
"fmt"
"os"
"path/filepath"

"github.com/openshift-online/ocm-cli/pkg/config"
sdk "github.com/openshift-online/ocm-sdk-go"
auth "github.com/openshift-online/ocm-sdk-go/authentication"
cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
"github.com/openshift/ocm-container/pkg/engine"
"github.com/openshift/osdctl/pkg/utils"
log "github.com/sirupsen/logrus"
)

const (
productionURL = "https://api.openshift.com"
stagingURL = "https://api.stage.openshift.com"
integrationURL = "https://api.integration.openshift.com"
productionGovURL = "https://api.openshiftusgov.com"

ocmConfigDest = "/root/.config/ocm/ocm.json"
ocmConfigMountOpts = "ro" // This should stay read-only, to keep the container from impacting the external environment

ocmContainerClientId = "ocm-cli"
)

// supprotedUrls is a shortened list of the urlAliases, for the help message
// SupportedUrls is a shortened list of the urlAliases, for the help message
// We actually support all the urlAliases, but that's too many for the help
var (
defaultOcmScopes = []string{"openid"}

SupportedUrls = []string{
"prod",
"stage",
@@ -58,19 +69,124 @@ const (
)

type Config struct {
Env map[string]string
Env map[string]string
Mounts []engine.VolumeMount
}

func New(ocmUrl string) (*Config, error) {
c := &Config{}

c.Env = make(map[string]string)

// OCM URL is required by the OCM CLI inside the container
// otherwise the URL will be overridden by the saved OCM config
c.Env["OCM_URL"] = url(ocmUrl)
c.Env["OCMC_OCM_URL"] = url(ocmUrl)

if c.Env["OCM_URL"] == "" {
if c.Env["OCMC_OCM_URL"] == "" {
return c, errInvalidOcmUrl
}

ocmConfig, err := config.Load()
if err != nil {
return c, err
}

if ocmConfig == nil {
ocmConfig = new(config.Config)
}

armed, reason, err := ocmConfig.Armed()
if err != nil {
return c, fmt.Errorf("error checking OCM config arming: %s", err)
}

var token string

if !armed {
log.Debugf("not logged into OCM: %s", reason)
token, err = auth.InitiateAuthCode(ocmContainerClientId)
if err != nil {
return c, fmt.Errorf("error initiating auth code: %s", err)
}
} else {
log.Debug("already logged into OCM")
token = ocmConfig.AccessToken
}

if config.IsEncryptedToken(token) {
log.Debug("OCM token is encrypted; assuming it is a RefreshToken")
ocmConfig.AccessToken = ""
ocmConfig.RefreshToken = token
} else {
log.Debug("OCM token is not encrypted; assuming it is an AccessToken")

parsedToken, err := config.ParseToken(token)
if err != nil {
return c, fmt.Errorf("error parsing token: %s", err)
}

typ, err := config.TokenType(parsedToken)
if err != nil {
return c, fmt.Errorf("error determining token type: %s", err)
}

switch typ {
case "Bearer", "":
log.Debug("token type is Bearer or empty; assuming it is an AccessToken")
ocmConfig.AccessToken = token
case "Refresh":
log.Debug("token type is Refresh; assuming it is a RefreshToken")
ocmConfig.AccessToken = ""
ocmConfig.RefreshToken = token
default:
return c, fmt.Errorf("unknown token type: %s", typ)
}

}

ocmConfig.ClientID = ocmContainerClientId
ocmConfig.TokenURL = sdk.DefaultTokenURL
ocmConfig.Scopes = defaultOcmScopes
// note - purposely not setting the ocmConfig.URL here
// to prevent overwriting the URL *outside* of the container
// The gateway is set by the OCM_URL env inside the container. See above.

connection, err := ocmConfig.Connection()
if err != nil {
return c, fmt.Errorf("error creating OCM connection: %s", err)
}

accessToken, refreshToken, err := connection.Tokens()
if err != nil {
return c, fmt.Errorf("error getting OCM tokens: %s", err)
}

ocmConfig.AccessToken = accessToken
ocmConfig.RefreshToken = refreshToken

err = config.Save(ocmConfig)
if err != nil {
log.Warnf("non-fatal error saving OCM config: %s", err)
}

ocmConfigLocation, err := config.Location()
if err != nil {
return c, fmt.Errorf("unable to identify OCM config location: %s", err)
}

ocmVolume := engine.VolumeMount{
Source: ocmConfigLocation,
Destination: ocmConfigDest,
MountOptions: ocmConfigMountOpts,
}

_, err = os.Stat(ocmVolume.Source)
if !os.IsNotExist(err) {

c.Mounts = append(c.Mounts, ocmVolume)
}

return c, nil
}

@@ -109,33 +225,3 @@ func GetClusterId(ocmClient *sdk.Connection, key string) (string, error) {

return cluster.ID(), err
}

// Finds the OCM Configuration file and returns the path to it
// Taken wholesale from openshift-online/ocm-cli
func GetOCMConfigLocation() (string, error) {
if ocmconfig := os.Getenv("OCM_CONFIG"); ocmconfig != "" {
return ocmconfig, nil
}

// Determine home directory to use for the legacy file path
home, err := os.UserHomeDir()
if err != nil {
return "", err
}

path := filepath.Join(home, ".ocm.json")

_, err = os.Stat(path)
if os.IsNotExist(err) {
// Determine standard config directory
configDir, err := os.UserConfigDir()
if err != nil {
return path, err
}

// Use standard config directory
path = filepath.Join(configDir, "/ocm/ocm.json")
}

return path, nil
}
1 change: 0 additions & 1 deletion pkg/ocmcontainer/envs.go
Original file line number Diff line number Diff line change
@@ -45,7 +45,6 @@ func ocmContainerEnvs() map[string]string {
}

// Handle some deprecations
e["OFFLINE_ACCESS_TOKEN"] = e["OCMC_OFFLINE_ACCESS_TOKEN"]
e["INITIAL_CLUSTER_LOGIN"] = e["OCMC_CLUSTER_ID"]

return e
15 changes: 1 addition & 14 deletions pkg/ocmcontainer/ocmcontainer.go
Original file line number Diff line number Diff line change
@@ -125,26 +125,13 @@ func New(cmd *cobra.Command, args []string) (*ocmContainer, error) {
maps.Copy(c.Envs, backplaneConfig.Env)
c.Volumes = append(c.Volumes, backplaneConfig.Mounts...)

// Copy the ocm config into the container
ocmConfigLocation, err := ocm.GetOCMConfigLocation()
if err != nil {
return o, err
}

ocmVolume := engine.VolumeMount{
Source: ocmConfigLocation,
Destination: "/root/.config/ocm/ocm.json",
MountOptions: "ro",
}

c.Volumes = append(c.Volumes, ocmVolume)

ocmConfig, err := ocm.New(viper.GetString("ocm-url"))
if err != nil {
return o, err
}

maps.Copy(c.Envs, ocmConfig.Env)
c.Volumes = append(c.Volumes, ocmConfig.Mounts...)

// OCM-Container optional features follow:

17 changes: 17 additions & 0 deletions utils/bashrc.d/00-ocm-libs.bashrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# shellcheck shell=bash

## NOTE: This file is intended for functions/aliases, etc that are
## NOT executed automatically on login.

# Wrap the ocm backplane console command to handle automation for
# port mapping inside the container
ocm() {
if [[ "${*}" =~ "backplane console" ]]
then
shift 2
echo "/root/.local/bin/cluster-console ${*}"
command /root/.local/bin/cluster-console
else
command ocm "$@"
fi
}
24 changes: 0 additions & 24 deletions utils/bashrc.d/00-ocm.bashrc

This file was deleted.

3 changes: 0 additions & 3 deletions utils/bashrc.d/01-aws.bashrc

This file was deleted.

File renamed without changes.
7 changes: 0 additions & 7 deletions utils/bashrc.d/04-kube-ps1.bashrc

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
# shellcheck shell=bash

function cluster_info_env_export(){
SEARCH_STRING="id like '$INITIAL_CLUSTER_LOGIN' or external_id like '$INITIAL_CLUSTER_LOGIN' or display_name like '$INITIAL_CLUSTER_LOGIN'"
@@ -9,14 +9,6 @@ function cluster_info_env_export(){
export CLUSTER_ID CLUSTER_UUID CLUSTER_NAME
}

# oc config current-context will return a 1 for newly-opened ocm-container
# This prevents another attempt at login if using a terminal multiplexer
if ! oc config current-context &>/dev/null && [ -n "$INITIAL_CLUSTER_LOGIN" ]
then
sre-login $INITIAL_CLUSTER_LOGIN
cluster_info_env_export
fi

function cluster_function() {
info="$(ocm backplane status 2> /dev/null)"
if [ $? -ne 0 ]; then return; fi
2 changes: 1 addition & 1 deletion utils/bashrc.d/08-vim.bashrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
# shellcheck shell=sh

## Set Defaults
export EDITOR=vim
Loading

0 comments on commit 2d9e91d

Please sign in to comment.