Compare commits

..

5 Commits

Author SHA1 Message Date
Boris Kuschel
35bd8835df Update README.md 2020-01-20 08:37:20 -05:00
Boris Kuschel
c1799deeef Add issue about kustomize speed 2020-01-20 08:36:11 -05:00
Boris Kuschel
837b88f3c8 Formatting fixups 2020-01-20 08:31:55 -05:00
Boris Kuschel
880f7cb29c Update README.md 2020-01-20 08:28:55 -05:00
Boris Kuschel
c7d93e2652 Add README.md
Signed-off-by: Boris Kuschel <boris.kuschel@qlik.com>
2020-01-20 08:27:19 -05:00
113 changed files with 2747 additions and 15361 deletions

60
.circleci/config.yml Normal file
View File

@@ -0,0 +1,60 @@
# Golang CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-go/ for more details
version: 2
jobs:
build:
docker:
- image: circleci/golang:stretch
working_directory: /go/src/github.com/qlik-oss/sense-installer
steps:
- checkout
- run: make build
build_release:
docker:
- image: circleci/golang:stretch
working_directory: /go/src/github.com/qlik-oss/sense-installer
steps:
- checkout
- run: make xbuild-all
- run:
name: "Build latest master from porter repo"
command: |
export GO111MODULE=off
go get -u get.porter.sh/porter || true
cd /go/src/get.porter.sh/porter
# store porter master commit
git rev-parse HEAD > /go/porter-master-commit.txt
make xbuild-all VERSION=latest
cp -r bin/latest/* /go/src/github.com/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}/bin/${CIRCLE_TAG}/
- run:
name: "Publish Release on GitHub"
command: |
go get github.com/tcnksm/ghr
# VERSION=v$(./artifacts/qliksense-linux-amd64 version | sed -nre 's/^[^0-9]*(([0-9]+\.)*[0-9]+).*/\1/p')
PORTER_REPO_COMMIT=$(cat /go/porter-master-commit.txt)
ghr -t ${GITHUB_TOKEN} -u ${CIRCLE_PROJECT_USERNAME} -r ${CIRCLE_PROJECT_REPONAME} -c ${CIRCLE_SHA1} -b "porter build based on commit: https://github.com/deislabs/porter/commit/${PORTER_REPO_COMMIT}" -delete ${CIRCLE_TAG} /go/src/github.com/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}/bin/${CIRCLE_TAG}/
workflows:
version: 2
commit:
jobs:
- build:
filters:
branches:
only: master
build_release:
jobs:
- build:
filters:
branches:
ignore: /.*/
tags:
only: /v.*/
- build_release:
requires:
- build
filters:
branches:
ignore: /.*/
tags:
only: /v.*/

5
.gitattributes vendored
View File

@@ -1,5 +0,0 @@
# Ignore all files and folders that start with .; .circleci, .github, .git, etc.
# Warning! This will ignore files in subfolders as well.
# If you needs files starting with . then change condition below to be specific
# for each file and folder that needs to be ignored
.* export-ignore

View File

@@ -1,46 +0,0 @@
name: Build Sense installer
on: [pull_request]
jobs:
test:
name: Test
env:
CGO_ENABLED: 0
strategy:
matrix:
go: [1.13.x]
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Set up Go ${{ matrix.go }}
uses: actions/setup-go@v2-beta
with:
go-version: ${{ matrix.go }}
- uses: actions/checkout@v2
- name: setup make (Windows)
if: matrix.os == 'windows-latest'
run: choco install make -y
- run: make test
build:
name: Build
runs-on: ubuntu-latest
needs: test
steps:
- name: Set up Go 1.13
uses: actions/setup-go@v2-beta
with:
go-version: 1.13
- uses: actions/checkout@v2
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
- run: make xbuild-all

View File

@@ -1,21 +0,0 @@
name: Publish docs via GitHub Pages
on:
push:
branches:
- master
paths:
- 'docs/**'
- 'mkdocs.yml'
jobs:
build:
name: Deploy docs
runs-on: ubuntu-latest
steps:
- name: Checkout master
uses: actions/checkout@v1
- name: Deploy docs
uses: mhausenblas/mkdocs-deploy-gh-pages@1.11
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,30 +0,0 @@
name: Release Sense installer binaries
on:
push:
tags:
- 'v*.*.*'
jobs:
release:
name: Build
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.13
uses: actions/setup-go@v2-beta
with:
go-version: 1.13
- uses: actions/checkout@v2
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/* # Needed in makefile for versioning
- run: make test
- run: make xbuild-all
- name: Release
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
files: bin/**/*

9
.gitignore vendored
View File

@@ -1,11 +1,2 @@
bin
.vscode
cmd/qliksense/__debug_bin
pkg/qliksense/crds
pkg/qliksense/packrd
pkg/qliksense/qliksense-packr.go
pkg/qliksense/docker-registry
/pkg/qliksense/tests
.DS_Store
.idea/

628
.qliksense/porter-runtime Normal file

File diff suppressed because one or more lines are too long

628
.qliksense/porter.exe Normal file

File diff suppressed because one or more lines are too long

191
LICENSE
View File

@@ -1,191 +0,0 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2019 QlikTech International AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,23 +0,0 @@
# Qlik Sense installer documentation
## Local development of documentation
Documentation is built using [mkdocs](https://www.mkdocs.org/) and uses [Material for MKDocs theme](https://squidfunk.github.io/mkdocs-material/)
Requirements: Python and PIP or Docker
```console
pip install mkdocs
pip install mkdocs-material
```
View live changes locally at http://localhost:8000
```console
mkdocs serve
```
### Docker
```console
docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material
```

View File

@@ -4,15 +4,13 @@ PKG = github.com/qlik-oss/sense-installer
MAKE_OPTS ?= --no-print-directory
LDFLAGS = -w -X $(PKG)/pkg.Version=$(VERSION) -X $(PKG)/pkg.Commit=$(COMMIT) -X "$(PKG)/pkg.CommitDate=$(COMMIT_DATE)"
XBUILD = CGO_ENABLED=0 go build -a -tags "$(BUILDTAGS)" -ldflags '$(LDFLAGS)'
XBUILD = CGO_ENABLED=0 go build -a -tags netgo -ldflags '$(LDFLAGS)'
BINDIR = bin
COMMIT ?= $(shell git rev-parse --short HEAD)
COMMIT_DATE ?= $(shell git show --no-patch --no-notes --pretty='%cd' $(COMMIT) --date=iso)
VERSION ?= $(shell git describe --tags 2> /dev/null || echo v0)
PERMALINK ?= $(shell git describe --tags --exact-match &> /dev/null && echo latest || echo canary)
BUILDTAGS = netgo containers_image_ostree_stub exclude_graphdriver_devicemapper exclude_graphdriver_btrfs containers_image_openpgp
CLIENT_PLATFORM ?= $(shell go env GOOS)
CLIENT_ARCH ?= $(shell go env GOARCH)
@@ -24,13 +22,8 @@ SUPPORTED_ARCHES = amd64
MIXIN = qliksense
DEVNUL := /dev/null
WHICH := which
ifeq ($(CLIENT_PLATFORM),windows)
FILE_EXT=.exe
DEVNUL := NUL
WHICH := where
else ifeq ($(RUNTIME_PLATFORM),windows)
FILE_EXT=.exe
else
@@ -38,78 +31,18 @@ FILE_EXT=
endif
.PHONY: build
build: clean generate
go run _make_support/mkdir_all/do.go $(BINDIR)
go build -ldflags '$(LDFLAGS)' -tags "$(BUILDTAGS)" -o $(BINDIR)/$(MIXIN)$(FILE_EXT) ./cmd/$(MIXIN)
$(MAKE) clean
build:
mkdir -p $(BINDIR)
go build -ldflags '$(LDFLAGS)' -o $(BINDIR)/$(MIXIN)$(FILE_EXT) ./cmd/$(MIXIN)
.PHONY: test-setup
test-setup: clean generate
ifeq ($(shell ${WHICH} docker-registry 2>${DEVNUL}),)
$(eval TMP-docker-distribution := $(shell go run _make_support/get_tmp_dir/do.go))
git clone https://github.com/docker/distribution.git "$(TMP-docker-distribution)/docker-distribution"
cd "$(TMP-docker-distribution)/docker-distribution" && git checkout -b v2.7.1 && "$(MAKE)"
go run _make_support/copy/do.go --src "$(TMP-docker-distribution)/docker-distribution/bin/registry" --dst pkg/qliksense/docker-registry$(FILE_EXT)
go run _make_support/remove_all/do.go "$(TMP-docker-distribution)"
endif
.PHONY: test-short
test-short: test-setup
go test -count 1 -p 1 -tags "$(BUILDTAGS)" -v -short ./...
"$(MAKE)" clean
.PHONY: test
test: test-setup
go test -count 1 -p 1 -tags "$(BUILDTAGS)" -v ./...
"$(MAKE)" clean
xbuild-all: clean generate
xbuild-all:
$(foreach OS, $(SUPPORTED_PLATFORMS), \
$(foreach ARCH, $(SUPPORTED_ARCHES), \
$(MAKE) $(MAKE_OPTS) CLIENT_PLATFORM=$(OS) CLIENT_ARCH=$(ARCH) MIXIN=$(MIXIN) xbuild; \
))
$(MAKE) clean
$(foreach ARCH, $(SUPPORTED_ARCHES), \
$(MAKE) $(MAKE_OPTS) CLIENT_PLATFORM=$(OS) CLIENT_ARCH=$(ARCH) MIXIN=$(MIXIN) xbuild; \
))
xbuild: $(BINDIR)/$(VERSION)/$(MIXIN)-$(CLIENT_PLATFORM)-$(CLIENT_ARCH)$(FILE_EXT)
$(BINDIR)/$(VERSION)/$(MIXIN)-$(CLIENT_PLATFORM)-$(CLIENT_ARCH)$(FILE_EXT):
mkdir -p $(dir $@)
GOOS=$(CLIENT_PLATFORM) GOARCH=$(CLIENT_ARCH) $(XBUILD) -o $@ ./cmd/$(MIXIN)
ifeq ($(CLIENT_PLATFORM),windows)
zip $(BINDIR)/$(VERSION)/$(MIXIN)-$(CLIENT_PLATFORM)-$(CLIENT_ARCH).zip $(BINDIR)/$(VERSION)/$(MIXIN)-$(CLIENT_PLATFORM)-$(CLIENT_ARCH)$(FILE_EXT)
else
tar -czvf $(BINDIR)/$(VERSION)/$(MIXIN)-$(CLIENT_PLATFORM)-$(CLIENT_ARCH).tar.gz -C $(BINDIR)/$(VERSION)/ $(MIXIN)-$(CLIENT_PLATFORM)-$(CLIENT_ARCH)$(FILE_EXT)
endif
upx $(BINDIR)/$(VERSION)/$(MIXIN)-$(CLIENT_PLATFORM)-$(CLIENT_ARCH)$(FILE_EXT)
generate: get-crds packr2
go generate ./...
go run _make_support/remove_all/do.go pkg/qliksense/crds
packr2:
ifeq ($(shell ${WHICH} packr2 2>${DEVNUL}),)
go get -u github.com/gobuffalo/packr/v2/packr2@v2.7.1
endif
clean: clean-packr
go run _make_support/remove_all/do.go pkg/qliksense/crds
clean-packr: packr2
cd pkg/qliksense && packr2 clean
get-crds:
ifeq ($(QLIKSENSE_OPERATOR_DIR),)
$(eval TMP-operator := $(shell go run _make_support/get_tmp_dir/do.go))
git clone https://github.com/qlik-oss/qliksense-operator.git -b master $(TMP-operator)/operator
"$(MAKE)" QLIKSENSE_OPERATOR_DIR="$(TMP-operator)/operator" get-crds
go run _make_support/remove_all/do.go "$(TMP-operator)"
else
go run _make_support/mkdir_all/do.go pkg/qliksense/crds/cr
go run _make_support/mkdir_all/do.go pkg/qliksense/crds/crd
go run _make_support/mkdir_all/do.go pkg/qliksense/crds/crd-deploy
go run _make_support/copy/do.go --src-pattern "$(QLIKSENSE_OPERATOR_DIR)/deploy/*.yaml" --dst pkg/qliksense/crds/crd-deploy
go run _make_support/copy/do.go --src-pattern "$(QLIKSENSE_OPERATOR_DIR)/deploy/crds/*_crd.yaml" --dst pkg/qliksense/crds/crd
go run _make_support/copy/do.go --src-pattern "$(QLIKSENSE_OPERATOR_DIR)/deploy/crds/*_cr.yaml" --dst pkg/qliksense/crds/cr
endif

124
README.md
View File

@@ -1,21 +1,123 @@
# (WIP) Qlik Sense on Kubernetes installation and operations CLI
## Documentation
To learn more about Qlik Sense on Kubernetes CLI go to https://qlik-oss.github.io/sense-installer/
# Qlik Sense installation and operations CLI
- [Qlik Sense installation and operations CLI](#qlik-sense-installation-and-operations-cli)
- [About](#about)
- [Future Direction](#future-direction)
- [Getting Started](#getting-started)
- [Requirements](#requirements)
- [Download](#download)
- [Generate Credentials from published bundle](#generate-credentials-from-published-bundle)
- [Qlik Sense version and image list](#qliksense-version-and-image-list)
- [Optional: Pulling images in manifest locally, "air gap"](#optional-pulling-images-in-manifest-locally-%22air-gap%22)
- [Running Preflight checks](#running-preflight-checks)
- [Installation](#installation)
- [Supported Parameters during install](#supported-parameters-during-install)
- [How To Add Identity Provider Config](#how-to-add-identity-provider-config)
- [Packaging a Custom bundle](#packaging-a-custom-bundle)
## About
The QSEoK CLI (qliksense) provides an imperative interface to many of the configurations that need to be applied against the declarative structure described in [qliksense-k8s](https://github.com/qlik-oss/qliksense-k8s).
The Qlik Sense installer CLI (sense-installer) provides an imperitive interface to many of the configurations that need to be applied against the declaritive structure described in (https://github.com/qlik-oss/qliksense-k8s)[https://github.com/qlik-oss/qliksense-k8s].
This is a technology preview that uses Qlik modified [kustomize](https://github.com/qlik-oss/kustomize) to kubernetes manifests of the versions of the [qliksense-k8s](https://github.com/qlik-oss/qliksense-k8s) repository.
This is a technology preview that uses (porter)[https://porter.sh] to execute "actions" (operations) and bundle versions of the (qliksense-k8s)[https://github.com/qlik-oss/qliksense-k8s] repository.
For each version of a qliksense edge build there should be a corresponding release in [qliksense-k8s] repository under [releases](https://github.com/qlik-oss/qliksense-k8s/releases)
These bundles are posted to (docker hub)[https://hub.docker.com/] at the following location: (https://hub.docker.com/r/qlik/qliksense-cnab-bundle)[https://hub.docker.com/r/qlik/qliksense-cnab-bundle/tags].
For each version of a qliksense sense edge build there should be a corresponding release current posted on docker hub. ex. `qlik/qliksense-cnab-bundle:v1.21.23-edge` for `v1.21.23` edge release of qliksense. The latest version posted will also be labelled as `latest`
### Future Direction
- Porter is currently used as a core technology for the CLI. In the future Porter will be moved "up the stack" to allow the CLI to perform the current and expanded operations independently and encapsulate core functionality currently provided by Porter and other dependent tooling.
- More operations:
- Expand preflight checks
- Expanded preflight checks
- backup/restore operations
- fully support airgap installation of QSEoK
- restore unwanted deletion of kubernetes resources
## Getting Started
### Requirements
- Docker Client connected to a docker engine into which images can built, pulled and pushed.
- (Docker Desktop setup tested for these instructions)
### Download
- Download the appropriate executable for your platform from the [releases page](https://github.com/qlik-oss/sense-installer/releases).
- Two environment variables will need to be set so as not to conflict with an existing porter installation:
- _Bash_
```shell
bash# export PORTER_HOME="$HOME\.qliksense"
bash# export PATH="$HOME\.qliksense;$PATH"
```
- _PowerShell_
```shell
PS> $Env:PORTER_HOME="$Env:USERPROFILE\.qliksense"
PS> $Env:PATH="$Env:USERPROFILE\.qliksense;$Env:PATH"
```
- To allow the CLI to download and initialize dependencies (including porter and it's associated mixins), simply execute `qliksense` with no arguments
- `qliksense`
### Generate Credentials from published bundle
- Ensure connectivity to the target cluster create a kubeconfig credential for a target bundle run ex.
- `porter cred generate <credential_name> --tag qlik/qliksense-cnab-bundle:v1.21.23-edge`
, replace `<credential_name>` with a name of your choosing.
- Select `file path` and specify full path to a kube config file ex. _Bash_:
- `/home/user/.kube/config` or _PowerShell_ `C:\Users\user\.kube\config `
### Qlik Sense version and image list
It is possible verify the version of the (qliksense-k8s)[https://github.com/qlik-oss/qliksense-k8s] repository bundled into the `qlik/qliksense-cnab-bundle` image and retreive the list of images included in that release. (This operation can take a minute or so)<https://github.com/qlik-oss/kustomize/issues/13> as the entire manifests needs to be rendered:
- `qliksense about --tag qlik/qliksense-cnab-bundle:<qliksense_version>`
### Optional: Pulling images in manifest locally, "air gap"
If the `dockerRegistry` parameter is specified as the private docker registry to be used by the kubernetes cluster hosting qliksense, it is possible to pull images to the local docker engine for an eventual push during a `qliksense install` or `qliksense upgrade`
### Running Preflight checks
You can run preflight checks to ensure that the cluster is in a healthy state before installing Qliksense.
- `qliksense preflight -c <credential_name> --tag qlik/qliksense-cnab-bundle:<qliksense_version>`
The above command runs the checks in the default namespace. If you want to specify the namespace to run preflight checks on:
- `qliksense preflight --param namespace=<value> -c <credential_name> --tag qlik/qliksense-cnab-bundle:<qliksense_version>`
### Installation
- Install the bundle : `qliksense install --param acceptEULA=yes -c <credential_name> --tag qlik/qliksense-cnab-bundle:<qliksense_version>`
#### Supported Parameters during install
| Name | Descriptions | Default |
| ------------- |:-------------:| -----:|
| profile | select a profile i.e docker-desktop, aws-eks, gke | docker-desktop |
| acceptEULA | yes | has to be yes |
| namespace | any kubernetes namespace | default |
| dockerRegistry | A private docker image regitry for pods | not specified (public) |
| rotateKeys | regenerate application PKI keys on upgrade (yes/no) | no |
| mongoDbUri | the mongodb URI to use | URI of development mongodb |
| scName | storage class name | none |
#### How To Add Identity Provider Config
Since idp configs are usually multiline configs it is not conventional to pass to porter during install as a `param`. Rather put the configs in a file and refer to that file during `porter install` command. For example to add `keycloak` IDP create file named `idpconfigs.txt` and put
```shell
idpConfigs=[{"discoveryUrl":"http://keycloak-insecure:8089/keycloak/realms/master22/.well-known/openid-configuration","clientId":"edge-auth","clientSecret":"e15b5075-9399-4b20-a95e-023022aa4aed","realm":"master","hostname":"elastic.example","claimsMapping":{"sub":["sub","client_id"],"name":["name","given_name","family_name","preferred_username"]}}]
```
Then pass that file during install command like this
```shell
porter install --param acceptEULA=yes -c <credential_name> --param-file idpconfigs.txt --tag qlik/qliksense-cnab-bundle:<qliksense_version>`
```
## Packaging a Custom bundle
If files need to be added to the (qliksense-k8s repository)[https://github.com/qlik-oss/qliksense-k8s] in order to perform advanced configuration outside the scope of the what the operator provides, a custom bundle needs to be built.
Packaging of Qlik Sense on Kubernetes is done through a [Porter](https://porter.sh/) definition in the [Qlik Sense on Kubernetes configuration repository](https://github.com/qlik-oss/qliksense-k8s/blob/master/porter.yaml), the resulting bundle published on DockerHub as a [Cloud Natvie Application Bundle](https://cnab.io/) called [qliksense-cnab-bundle](https://hub.docker.com/r/qlik/qliksense-cnab-bundle)
To start, clone (https://github.com/qlik-oss/qliksense-k8s)[https://github.com/qlik-oss/qliksense-k8s] and modify the repo as desired, once finished make sure to be in the `qliksense-k8s` directory from which the porter bundle can be built:
- `porter build`
Once built, all of the `porter` command that were used with `--tag` can be now be used without this flag provided that porter is executed with the `qliksense-k8s` directory. `porter` will automatically use the qliksense-k8s (and the porter.yaml) in the current directory.

View File

@@ -1,109 +0,0 @@
package main
import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"github.com/otiai10/copy"
)
func main() {
srcPattern := flag.String("src-pattern", "", "Source file pattern")
src := flag.String("src", "", "Source file or directory")
dst := flag.String("dst", "", "Destination file or directory")
flag.Parse()
if *srcPattern != "" {
if dstInfo, err := os.Lstat(*dst); err != nil {
panic(err)
} else if !dstInfo.IsDir() {
panic(fmt.Errorf("%v must be a directory", *dst))
}
if matches, err := filepath.Glob(*srcPattern); err != nil {
panic(err)
} else {
for _, match := range matches {
srcInfo, err := os.Lstat(match)
if err != nil {
panic(err)
}
if srcInfo.IsDir() {
if err := copy.Copy(match, *dst, copy.Options{
OnSymlink: func(p string) copy.SymlinkAction {
return copy.Skip
},
}); err != nil {
panic(err)
}
} else if srcInfo.Mode().IsRegular() {
if err := fcopy(match, filepath.Join(*dst, filepath.Base(match)), srcInfo); err != nil {
panic(err)
}
}
}
}
} else if *src != "" {
srcInfo, err := os.Lstat(*src)
if err != nil {
panic(err)
}
if srcInfo.IsDir() {
if err := copy.Copy(*src, *dst, copy.Options{
OnSymlink: func(p string) copy.SymlinkAction {
return copy.Skip
},
}); err != nil {
panic(err)
}
} else if srcInfo.Mode().IsRegular() {
finalDestination := *dst
if dstInfo, err := os.Lstat(*dst); err != nil {
if !os.IsNotExist(err) {
panic(err)
}
} else if dstInfo.IsDir() {
finalDestination = filepath.Join(*dst, filepath.Base(*src))
} else if dstInfo.Mode().IsRegular() {
fmt.Println("WARNING: over-writing existing file: ", *dst)
if err := os.Remove(*dst); err != nil {
panic(err)
}
} else {
panic(fmt.Errorf("not sure how to copy to this dst: %v", *dst))
}
if err := fcopy(*src, finalDestination, srcInfo); err != nil {
panic(err)
}
}
}
}
func fcopy(src, dest string, info os.FileInfo) (err error) {
if err := os.MkdirAll(filepath.Dir(dest), os.ModePerm); err != nil {
return err
}
f, err := os.Create(dest)
if err != nil {
return err
}
defer f.Close()
if err = os.Chmod(f.Name(), info.Mode()); err != nil {
return err
}
s, err := os.Open(src)
if err != nil {
return err
}
defer s.Close()
_, err = io.Copy(f, s)
return err
}

View File

@@ -1,5 +0,0 @@
module github.com/qlik-oss/sense-installer/_make_support/copy
go 1.13
require github.com/otiai10/copy v1.1.1

View File

@@ -1,8 +0,0 @@
github.com/otiai10/copy v1.1.1 h1:PH7IFlRQ6Fv9vYmuXbDRLdgTHoP1w483kPNUP2bskpo=
github.com/otiai10/copy v1.1.1/go.mod h1:rrF5dJ5F0t/EWSYODDu4j9/vEeYHMkc8jt0zJChqQWw=
github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE=
github.com/otiai10/curr v1.0.0 h1:TJIWdbX0B+kpNagQrjgq8bCMrbhiuX73M2XwgtDMoOI=
github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs=
github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo=
github.com/otiai10/mint v1.3.1 h1:BCmzIS3n71sGfHB5NMNDB3lHYPz8fWSkCAErHed//qc=
github.com/otiai10/mint v1.3.1/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc=

View File

@@ -1,14 +0,0 @@
package main
import (
"fmt"
"io/ioutil"
)
func main() {
if tmpDir, err := ioutil.TempDir("", ""); err != nil {
panic(err)
} else {
fmt.Print(tmpDir)
}
}

View File

@@ -1,3 +0,0 @@
module github.com/qlik-oss/sense-installer/_make_support/get_tmp_dir
go 1.13

View File

@@ -1,11 +0,0 @@
package main
import (
"os"
)
func main() {
if err := os.MkdirAll(os.Args[1], os.ModePerm); err != nil {
panic(err)
}
}

View File

@@ -1,3 +0,0 @@
module github.com/qlik-oss/sense-installer/_make_support/mkdir_all
go 1.13

View File

@@ -1,11 +0,0 @@
package main
import (
"os"
)
func main() {
if err := os.RemoveAll(os.Args[1]); err != nil {
panic(err)
}
}

View File

@@ -1,3 +0,0 @@
module github.com/qlik-oss/sense-installer/_make_support/remove_all
go 1.13

View File

@@ -1,66 +0,0 @@
package main
import (
"errors"
"fmt"
"strings"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
)
type aboutCommandOptions struct {
Profile string
}
func about(q *qliksense.Qliksense) *cobra.Command {
opts := &aboutCommandOptions{}
c := &cobra.Command{
Use: "about ref",
Short: "Displays information pertaining to Qliksense on Kubernetes",
Long: "Gives the version of QLik Sense on Kubernetes and versions of images.",
Example: `
qliksense about 1.0.0
- display default profile (docker-desktop) for Git ref 1.0.0 in the qliksense-k8s repo
qliksense about 1.0.0 --profile=docker-desktop
- specifying profile
qliksense about
qliksense about --profile=test
- if no Git ref is provided, then get version information from the configuration on disk:
- if user's current directory has a subdirectory "manifests/${profile}",
then get version information from that
- if using other supported commands the user has built a CR in ~/.qliksense,
then get version information based on the path derived like so:
- ${spec.manifestsRoot}/${spec.profile} # if no profile flag provided
- ${spec.manifestsRoot}/${profile} # if profile is provided using the --profile command flag
- if no config found on disk in locations described above,
then get version information based on the default profile in the qliksense-k8s repo master
`,
RunE: func(cmd *cobra.Command, args []string) error {
if gitRef, err := getSingleArg(args); err != nil {
return err
} else if vout, err := q.About(gitRef, opts.Profile); err != nil {
return err
} else if out, err := yaml.Marshal(vout); err != nil {
return err
} else if _, err := fmt.Println(string(out)); err != nil {
return err
}
return nil
},
}
f := c.Flags()
f.StringVar(&opts.Profile, "profile", "", "Configuration profile")
return c
}
func getSingleArg(args []string) (string, error) {
if len(args) > 1 {
return "", errors.New("too many arguments, only 1 expected")
} else if len(args) == 1 {
return strings.TrimSpace(args[0]), nil
}
return "", nil
}

412
cmd/qliksense/aliases.go Normal file
View File

@@ -0,0 +1,412 @@
package main
import (
"bufio"
"os"
"strings"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func buildAliasCommands(porterCmd *cobra.Command, q *qliksense.Qliksense) []*cobra.Command {
return []*cobra.Command{
buildBuildAlias(porterCmd),
buildInstallAlias(porterCmd, q),
buildUpgradeAlias(porterCmd, q),
buildAboutAlias(porterCmd),
buildPreflightAlias(porterCmd, q),
buildUninstallAlias(porterCmd, q),
}
}
func buildBuildAlias(porterCmd *cobra.Command) *cobra.Command {
var (
c *cobra.Command
)
c = &cobra.Command{
Use: "build",
Short: "Build a bundle",
Long: "Builds the bundle in the current directory by generating a Dockerfile and a CNAB bundle.json, and then building the invocation image.",
DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
return porterCmd.RunE(porterCmd, append([]string{"build"}, args...))
},
Annotations: map[string]string{
"group": "alias",
},
}
return c
}
type paramOptions struct {
aboutOptions
Params []string
ParamFiles []string
Name string
InsecureRegistry bool
// CredentialIdentifiers is a list of credential names or paths to make available to the bundle.
CredentialIdentifiers []string
Driver string
Force bool
Insecure bool
}
func buildInstallAlias(porterCmd *cobra.Command, q *qliksense.Qliksense) *cobra.Command {
var (
c *cobra.Command
opts *paramOptions
registry *string
)
opts = &paramOptions{}
c = &cobra.Command{
Use: "install [INSTANCE]",
Short: "Install qliksense",
Long: `Install a new instance of a bundle.
The first argument is the bundle instance name to create for the installation. This defaults to the name of the bundle.
Porter uses the Docker driver as the default runtime for executing a bundle's invocation image, but an alternate driver may be supplied via '--driver/-d'.
For example, the 'debug' driver may be specified, which simply logs the info given to it and then exits.`,
Example: ` qliksense install
qliksense install --version v1.0.0
qliksense install --insecure
qliksense install qliksense --file qliksense/bundle.json
qliksense install --param-file base-values.txt --param-file dev-values.txt --param test-mode=true --param header-color=blue
qliksense install --cred kubernetes
qliksense install --driver debug
qliksense install MyAppFromTag --tag qlik/qliksense-cnab-bundle:v1.0.0
`,
//DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
// Push images here.
// TODO: Need to get the private reg from params
args = append(os.Args[2:], opts.getTagValue(args)...)
if registry = opts.findKey("dockerRegistry"); registry != nil {
if len(*registry) > 0 {
q.TagAndPushImages(*registry)
}
}
return porterCmd.RunE(porterCmd, append([]string{"install"}, args...))
},
Annotations: map[string]string{
"group": "alias",
},
}
f := c.Flags()
f.StringVarP(&opts.Version, "version", "v", "latest",
"Version of Qlik Sense to install")
f.BoolVar(&opts.Insecure, "insecure", true,
"Allow working with untrusted bundles")
f.StringVarP(&opts.File, "file", "f", "",
"Path to the porter manifest file. Defaults to the bundle in the current directory.")
f.StringVar(&opts.CNABFile, "cnab-file", "",
"Path to the CNAB bundle.json file.")
f.StringSliceVar(&opts.ParamFiles, "param-file", nil,
"Path to a parameters definition file for the bundle, each line in the form of NAME=VALUE. May be specified multiple times.")
f.StringSliceVar(&opts.Params, "param", nil,
"Define an individual parameter in the form NAME=VALUE. Overrides parameters set with the same name using --param-file. May be specified multiple times.")
f.StringSliceVarP(&opts.CredentialIdentifiers, "cred", "c", nil,
"Credential to use when installing the bundle. May be either a named set of credentials or a filepath, and specified multiple times.")
f.StringVarP(&opts.Driver, "driver", "d", "docker",
"Specify a driver to use. Allowed values: docker, debug")
f.StringVarP(&opts.Tag, "tag", "t", "",
"Use a bundle in an OCI registry specified by the given tag")
f.BoolVar(&opts.InsecureRegistry, "insecure-registry", false,
"Don't require TLS for the registry")
f.BoolVar(&opts.Force, "force", false,
"Force a fresh pull of the bundle and all dependencies")
return c
}
func buildUpgradeAlias(porterCmd *cobra.Command, q *qliksense.Qliksense) *cobra.Command {
var (
c *cobra.Command
opts *paramOptions
registry *string
)
opts = &paramOptions{}
c = &cobra.Command{
Use: "upgrade [INSTANCE]",
Short: "Upgrade qliksense",
Long: `Upgrade to a new instance of a bundle.
The first argument is the bundle instance name to upgrade for the installation. This defaults to the name of the bundle.
Porter uses the Docker driver as the default runtime for executing a bundle's invocation image, but an alternate driver may be supplied via '--driver/-d'.
For example, the 'debug' driver may be specified, which simply logs the info given to it and then exits.`,
Example: ` qliksense upgrade
qliksense upgrade --version v1.0.0
qliksense upgrade --insecure
qliksense upgrade qliksense --file qliksense/bundle.json
qliksense upgrade --param-file base-values.txt --param-file dev-values.txt --param test-mode=true --param header-color=blue
qliksense upgrade --cred kubernetes
qliksense upgrade --driver debug
qliksense upgrade MyAppFromTag --tag qlik/qliksense-cnab-bundle:v1.0.0
`,
//DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
// Push images here.
// TODO: Need to get the private reg from params
args = append(os.Args[2:], opts.getTagValue(args)...)
if registry = opts.findKey("dockerRegistry"); registry != nil {
if len(*registry) > 0 {
q.TagAndPushImages(*registry)
}
}
return porterCmd.RunE(porterCmd, append([]string{"upgrade"}, args...))
},
Annotations: map[string]string{
"group": "alias",
},
}
f := c.Flags()
f.StringVarP(&opts.Version, "version", "v", "latest",
"Version of Qlik Sense to upgrade to")
f.BoolVar(&opts.Insecure, "insecure", true,
"Allow working with untrusted bundles")
f.StringVarP(&opts.File, "file", "f", "",
"Path to the porter manifest file. Defaults to the bundle in the current directory.")
f.StringVar(&opts.CNABFile, "cnab-file", "",
"Path to the CNAB bundle.json file.")
f.StringSliceVar(&opts.ParamFiles, "param-file", nil,
"Path to a parameters definition file for the bundle, each line in the form of NAME=VALUE. May be specified multiple times.")
f.StringSliceVar(&opts.Params, "param", nil,
"Define an individual parameter in the form NAME=VALUE. Overrides parameters set with the same name using --param-file. May be specified multiple times.")
f.StringSliceVarP(&opts.CredentialIdentifiers, "cred", "c", nil,
"Credential to use when installing the bundle. May be either a named set of credentials or a filepath, and specified multiple times.")
f.StringVarP(&opts.Driver, "driver", "d", "docker",
"Specify a driver to use. Allowed values: docker, debug")
f.StringVarP(&opts.Tag, "tag", "t", "",
"Use a bundle in an OCI registry specified by the given tag")
f.BoolVar(&opts.InsecureRegistry, "insecure-registry", false,
"Don't require TLS for the registry")
f.BoolVar(&opts.Force, "force", false,
"Force a fresh pull of the bundle and all dependencies")
return c
}
func buildUninstallAlias(porterCmd *cobra.Command, q *qliksense.Qliksense) *cobra.Command {
var (
c *cobra.Command
opts *paramOptions
)
opts = &paramOptions{}
c = &cobra.Command{
Use: "uninstall [INSTANCE]",
Short: "Uninstall a bundle instance",
Long: `Uninstall a bundle instance
The first argument is the bundle instance name to uninstall. This defaults to the name of the bundle.
Porter uses the Docker driver as the default runtime for executing a bundle's invocation image, but an alternate driver may be supplied via '--driver/-d'.
For example, the 'debug' driver may be specified, which simply logs the info given to it and then exits.`,
Example: ` qliksense uninstall
qliksense uninstall --insecure
qliksense uninstall MyAppInDev --file myapp/bundle.json
qliksense uninstall --param-file base-values.txt --param-file dev-values.txt --param test-mode=true --param header-color=blue
qliksense uninstall --cred azure --cred kubernetes
qliksense uninstall --driver debug
qliksense uninstall MyAppFromTag --tag deislabs/porter-kube-bundle:v1.0
`,
RunE: func(cmd *cobra.Command, args []string) error {
return porterCmd.RunE(porterCmd, append([]string{"uninstall"}, os.Args[2:]...))
},
Annotations: map[string]string{
"group": "alias",
},
}
f := c.Flags()
f.BoolVar(&opts.Insecure, "insecure", true,
"Allow working with untrusted bundles")
f.StringVarP(&opts.File, "file", "f", "",
"Path to the porter manifest file. Defaults to the bundle in the current directory. Optional unless a newer version of the bundle should be used to uninstall the bundle.")
f.StringVar(&opts.CNABFile, "cnab-file", "",
"Path to the CNAB bundle.json file.")
f.StringSliceVar(&opts.ParamFiles, "param-file", nil,
"Path to a parameters definition file for the bundle, each line in the form of NAME=VALUE. May be specified multiple times.")
f.StringSliceVar(&opts.Params, "param", nil,
"Define an individual parameter in the form NAME=VALUE. Overrides parameters set with the same name using --param-file. May be specified multiple times.")
f.StringSliceVarP(&opts.CredentialIdentifiers, "cred", "c", nil,
"Credential to use when uninstalling the bundle. May be either a named set of credentials or a filepath, and specified multiple times.")
f.StringVarP(&opts.Driver, "driver", "d", "docker",
"Specify a driver to use. Allowed values: docker, debug")
f.StringVarP(&opts.Tag, "tag", "t", "",
"Use a bundle in an OCI registry specified by the given tag")
f.BoolVar(&opts.InsecureRegistry, "insecure-registry", false,
"Don't require TLS for the registry")
f.BoolVar(&opts.Force, "force", false,
"Force a fresh pull of the bundle and all dependencies")
return c
}
func (o *aboutOptions) getTagDefaults(args []string) []string {
args = append(args, o.getTagValue(args)...)
return args
}
func (o *aboutOptions) getTagValue(args []string) []string {
tagArr := []string{}
if len(o.Tag) > 1 {
tagArr = []string{"--tag", o.Tag}
}
if len(o.Tag) <= 0 && len(o.File) <= 0 && len(o.CNABFile) <= 0 {
if _, err := os.Stat("porter.yaml"); err != nil {
tagArr = []string{"--tag", "qlik/qliksense-cnab-bundle:" + o.Version}
}
}
return tagArr
}
type aboutOptions struct {
Version string
Tag string
File string
CNABFile string
}
func buildAboutAlias(porterCmd *cobra.Command) *cobra.Command {
var (
c *cobra.Command
opts *aboutOptions
)
opts = &aboutOptions{}
c = &cobra.Command{
Use: "about",
Short: "About Qlik Sense",
Long: "Gives the verion of QLik Sense on Kuberntetes and versions of images.",
RunE: func(cmd *cobra.Command, args []string) error {
args = opts.getTagDefaults(args)
return porterCmd.RunE(porterCmd, append([]string{"invoke", "--action", "about"}, args...))
},
Annotations: map[string]string{
"group": "alias",
},
}
f := c.Flags()
f.StringVarP(&opts.Version, "version", "v", "latest",
"Version of Qlik Sense to install")
f.StringVarP(&opts.Tag, "tag", "t", "",
"Use a bundle in an OCI registry specified by the given tag")
f.StringVarP(&opts.File, "file", "f", "",
"Path to the porter manifest file. Defaults to the bundle in the current directory.")
f.StringVar(&opts.CNABFile, "cnab-file", "",
"Path to the CNAB bundle.json file.")
return c
}
func buildPreflightAlias(porterCmd *cobra.Command, q *qliksense.Qliksense) *cobra.Command {
var (
c *cobra.Command
opts *paramOptions
)
opts = &paramOptions{}
c = &cobra.Command{
Use: "preflight",
Short: "Preflight Checks",
Long: "Perform Preflight Checks",
RunE: func(cmd *cobra.Command, args []string) error {
args = append(os.Args[1:], opts.getTagDefaults(args)...)
return porterCmd.RunE(porterCmd, append([]string{"invoke", "--action", "preflight"}, args...))
},
Annotations: map[string]string{
"group": "alias",
},
}
f := c.Flags()
f.StringSliceVar(&opts.Params, "param", nil,
"Define an individual parameter in the form NAME=VALUE. Overrides parameters set with the same name using --param-file. May be specified multiple times.")
f.StringSliceVar(&opts.ParamFiles, "param-file", nil,
"Path to a parameters definition file for the bundle, each line in the form of NAME=VALUE. May be specified multiple times.")
f.StringVarP(&opts.Tag, "tag", "t", "",
"Use a bundle in an OCI registry specified by the given tag")
f.StringVarP(&opts.Version, "version", "v", "latest",
"Version of Qlik Sense to install")
f.StringSliceVarP(&opts.CredentialIdentifiers, "cred", "c", nil,
"Credential to use when installing the bundle. May be either a named set of credentials or a filepath, and specified multiple times.")
return c
}
func (o *paramOptions) findKey(param string) *string {
var (
value *string
)
if value = o.findParams(param); value != nil {
return value
}
if value = o.findParamFiles(param); value != nil {
return value
}
return nil
}
// parsedParams parses the variable assignments in Params.
func (o *paramOptions) findParams(param string) *string {
return o.findVariableKey(param, o.Params)
}
// parseParamFiles parses the variable assignments in ParamFiles.
func (o *paramOptions) findParamFiles(param string) *string {
var (
path string
retStr *string
)
for _, path = range o.ParamFiles {
retStr = o.findParamFile(param, path)
}
return retStr
}
func (o *paramOptions) findParamFile(param string, path string) *string {
var (
f *os.File
err error
scanner *bufio.Scanner
lines []string
retStr *string
)
if f, err = os.Open(path); err == nil {
defer f.Close()
scanner = bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
retStr = o.findVariableKey(param, lines)
}
return retStr
}
func (o *paramOptions) findVariableKey(param string, params []string) *string {
var (
variable, value string
)
for _, p := range params {
parts := strings.SplitN(p, "=", 2)
if len(parts) >= 2 {
variable = strings.TrimSpace(parts[0])
if variable == param {
value = strings.TrimSpace(parts[1])
return &value
}
}
}
return nil
}

View File

@@ -1,74 +0,0 @@
package main
import (
"bytes"
"errors"
"fmt"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func applyCmd(q *qliksense.Qliksense) *cobra.Command {
opts := &qliksense.InstallCommandOptions{}
filePath := ""
keepPatchFiles, pull, push := false, false, false
c := &cobra.Command{
Use: "apply",
Short: "install qliksense based on provided cr file",
Long: `install qliksense based on provided cr file`,
Example: `qliksense apply -f file_name or cat cr_file | qliksense apply -f -`,
RunE: func(cmd *cobra.Command, args []string) error {
return runLoadOrApplyCommandE(cmd, func(crBytes []byte) error {
if cr, crBytesWithEula, err := getCrWithEulaInserted(crBytes); err != nil {
return err
} else if err := validatePullPushFlagsOnApply(cr, pull, push); err != nil {
return err
} else {
return q.ApplyCRFromReader(bytes.NewReader(crBytesWithEula), opts, keepPatchFiles, true, pull, push)
}
})
},
}
f := c.Flags()
f.StringVarP(&filePath, "file", "f", "", "Install from a CR file")
c.MarkFlagRequired("file")
f.StringVarP(&opts.StorageClass, "storageClass", "s", "", "Storage class for qliksense")
f.StringVarP(&opts.MongodbUri, "mongodbUri", "m", "", "mongodbUri for qliksense (i.e. mongodb://qlik-default-mongodb:27017/qliksense?ssl=false)")
f.StringVarP(&opts.RotateKeys, "rotateKeys", "r", "", "Rotate JWT keys for qliksense (yes:rotate keys/ no:use exising keys from cluster/ None: use default EJSON_KEY from env")
f.BoolVar(&keepPatchFiles, keepPatchFilesFlagName, keepPatchFiles, keepPatchFilesFlagUsage)
f.BoolVarP(&pull, pullFlagName, pullFlagShorthand, pull, pullFlagUsage)
f.BoolVarP(&push, pushFlagName, pushFlagShorthand, push, pushFlagUsage)
eulaPreRunHooks.addValidator(fmt.Sprintf("%v %v", rootCommandName, c.Name()), loadOrApplyCommandEulaPreRunHook)
return c
}
func validatePullPushFlagsOnApply(cr *qapi.QliksenseCR, pull, push bool) error {
if pull && !push {
fmt.Printf("WARNING: pulling images without pushing them")
}
if push {
if registry := cr.Spec.GetImageRegistry(); registry == "" {
return errors.New("no image registry set in the CR; to set it use: qliksense config set-image-registry")
}
}
return nil
}
func getCrWithEulaInserted(crBytes []byte) (*qapi.QliksenseCR, []byte, error) {
if cr, err := qapi.CreateCRObjectFromString(string(crBytes)); err != nil {
return nil, nil, err
} else {
cr.SetEULA("yes")
if crBytesWithEula, err := qapi.K8sToYaml(cr); err != nil {
return nil, nil, err
} else {
return cr, crBytesWithEula, nil
}
}
}

View File

@@ -1,61 +0,0 @@
package main
import (
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func configCmd(q *qliksense.Qliksense) *cobra.Command {
var configCmd = &cobra.Command{
Use: "config",
Short: "do operations on/around CR",
Long: `do operations on/around CR`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.ConfigViewCR()
},
}
return configCmd
}
func configApplyCmd(q *qliksense.Qliksense) *cobra.Command {
c := &cobra.Command{
Use: "apply",
Short: "generate the patches and apply manifests to k8s",
Long: `generate patches based on CR and apply manifests to k8s`,
Example: `qliksense config apply`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.ConfigApplyQK8s()
},
}
return c
}
func configViewCmd(q *qliksense.Qliksense) *cobra.Command {
c := &cobra.Command{
Use: "view",
Short: "view the qliksense operator CR",
Long: `display the operator CR, that has been created for the current context`,
Example: `qliksense config view`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.ConfigViewCR()
},
}
return c
}
func configEditCmd(q *qliksense.Qliksense) *cobra.Command {
c := &cobra.Command{
Use: "edit [context-name]",
Short: "Edit the context cr",
Long: `edit the context cr. if no context name provided default context will be edited
It will open the vim editor unless KUBE_EDITOR is defined`,
Example: `qliksense config edit [context-name]`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 1 {
return q.EditCR(args[0])
}
return q.EditCR("")
},
}
return c
}

View File

@@ -1,246 +0,0 @@
package main
import (
"errors"
"fmt"
"os"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func setContextConfigCmd(q *qliksense.Qliksense) *cobra.Command {
var (
cmd *cobra.Command
)
cmd = &cobra.Command{
Use: "set-context",
Short: "Sets the context in which the Kubernetes cluster and resources live in",
Example: `
qliksense config set-context <context_name>
- The above configuration will be displayed in the CR
`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.SetContextConfig(args)
},
}
return cmd
}
func listContextConfigCmd(q *qliksense.Qliksense) *cobra.Command {
var (
cmd *cobra.Command
)
cmd = &cobra.Command{
Use: "list-contexts",
Short: "retrieves the contexts and lists them",
Example: `qliksense config list-contexts`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.ListContextConfigs()
},
}
return cmd
}
func setOtherConfigsCmd(q *qliksense.Qliksense) *cobra.Command {
var (
cmd *cobra.Command
)
cmd = &cobra.Command{
Use: "set",
Short: "configure a key value pair into the current context",
Example: `
qliksense config set <key>=<value>
- The above configuration will be displayed in the CR
`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.SetOtherConfigs(args)
},
}
return cmd
}
func setConfigsCmd(q *qliksense.Qliksense) *cobra.Command {
var (
cmd *cobra.Command
)
base64Encoded := false
cmd = &cobra.Command{
Use: "set-configs",
Short: "set configurations into the qliksense context as key-value pairs",
Example: `
qliksense config set-configs <service_name>.<attribute>="<value>"
- The above configuration will be displayed in the CR
qliksense config set-configs <service_name>.<attribute>="<value" --base64
- if the value is base64 encoded
echo "something" | base64 | qliksense config set-configs <service_name>.<attribute> --base64
- value is coming from input pipe as base64 encoded
echo "something" | qliksense config set-configs <service_name>.<attribute>
- value is coming from input pipe
`,
RunE: func(cmd *cobra.Command, args []string) error {
if isInputFromPipe() && len(args) == 1 {
return q.SetConfigFromReader(args[0], os.Stdin, base64Encoded)
}
return q.SetConfigs(args, base64Encoded)
},
}
f := cmd.Flags()
f.BoolVarP(&base64Encoded, "base64", "", false, "if the arguments value is base64 encoded")
return cmd
}
func setSecretsCmd(q *qliksense.Qliksense) *cobra.Command {
var (
cmd *cobra.Command
secret bool
)
base64Encoded := false
cmd = &cobra.Command{
Use: "set-secrets",
Short: "set secrets configurations into the qliksense context as key-value pairs",
Example: `
qliksense config set-secrets <service_name>.<attribute>="<value>" --secret=true
- Encrypt the secret value into a new Kubernetes secret resource
- The secret resource is placed in the location: <qliksense_home>/<contexts>/<context_name>/secrets/<service_name>.yaml
- Include it's key reference in the current context
qliksense config set-secrets <service_name>.<attribute>="<value>" --secret=false
- Encrypt the secret value and display it in the current context
- No secret resource is created
- The above configuration will be displayed in the CR
qliksense config set-secrets <service_name>.<attribute>="<value>" --base64
- the <value> is base64 encoded
echo "something" | base64 | qliksense config set-secrets <service_name>.<attribute> --base64
- value coming from input pipe as base64 encoded
echo "something" | qliksense config set-secrets <service_name>.<attribute>
- value coming from input pipe`,
RunE: func(cmd *cobra.Command, args []string) error {
if isInputFromPipe() && len(args) == 1 {
return q.SetSecretsFromReader(args[0], os.Stdin, secret, base64Encoded)
}
return q.SetSecrets(args, secret, base64Encoded)
},
}
f := cmd.Flags()
f.BoolVar(&secret, "secret", false, "Whether secrets should be encrypted as a Kubernetes Secret resource")
f.BoolVarP(&base64Encoded, "base64", "", false, "if the arguments value is base64 encoded")
return cmd
}
func deleteContextConfigCmd(q *qliksense.Qliksense) *cobra.Command {
var (
cmd *cobra.Command
)
skipConfirmation := false
cmd = &cobra.Command{
Use: "delete-context",
Short: "deletes a specific context locally (not in-cluster)",
Example: `qliksense config delete-contexts <context_name>`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.DeleteContextConfig(args, skipConfirmation)
},
}
f := cmd.Flags()
f.BoolVar(&skipConfirmation, "yes", skipConfirmation, "skips confirmation")
return cmd
}
func setImageRegistryCmd(q *qliksense.Qliksense) *cobra.Command {
var (
cmd *cobra.Command
pushUsername string
pushPassword string
pullUsername string
pullPassword string
username string
password string
)
cmd = &cobra.Command{
Use: "set-image-registry",
Short: "set private image registry",
Example: `
qliksense config set-image-registry https://your.private.registry.example.com:5000 --push-username foo1 --push-password bar1 --pull-username foo2 --pull-password bar2
qliksense config set-image-registry https://your.private.registry.example.com:5000 --username foo --password bar
`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("private docker image registry FQDN is required")
}
registry := args[0]
if username != "" {
pullUsername = username
pushUsername = username
}
if password != "" {
pullPassword = password
pushPassword = password
}
if (pullUsername != "" && pushUsername == "") || (pullUsername == "" && pushUsername != "") {
return errors.New("if you specify pull credentials, you must specify push credentials as well and vise versa")
}
if (pullUsername == "" && pullPassword != "") || (pushUsername == "" && pushPassword != "") {
return errors.New("if you specify passwords, you must specify usernames as well")
}
return q.SetImageRegistry(registry, pushUsername, pushPassword, pullUsername, pullPassword)
},
}
f := cmd.Flags()
f.StringVar(&pushUsername, "push-username", "", "Username used for pushing images")
f.StringVar(&pushPassword, "push-password", "", "Password used for pushing images")
f.StringVar(&pullUsername, "pull-username", "", "Username used for pulling images")
f.StringVar(&pullPassword, "pull-password", "", "Password used for pulling images")
f.StringVar(&username, "username", "", "Username used for both pushing and pulling images")
f.StringVar(&password, "password", "", "Password used for both pushing and pulling images")
return cmd
}
func cleanConfigRepoPatchesCmd(q *qliksense.Qliksense) *cobra.Command {
return &cobra.Command{
Use: "clean-config-repo-patches",
Short: "Clean config repo patch files",
Example: "qliksense config clean-config-repo-patches",
RunE: func(cmd *cobra.Command, args []string) error {
qConfig := qapi.NewQConfig(q.QliksenseHome)
if err := q.DiscardAllUnstagedChangesFromGitRepo(qConfig); err != nil {
return fmt.Errorf("error removing temporary changes to the config: %v\n", err)
}
fmt.Println("done")
return nil
},
}
}
func unsetCmd(q *qliksense.Qliksense) *cobra.Command {
cmd := &cobra.Command{
Use: "unset",
Short: "remove a key from a context or a secrets or a configs from the context",
Example: `
# remove the key from CR
qliksense config unset <key>
# remove the key from service inside configs/secrets of CR
qliksense config unset <service>.<key>
# remove the service from inside configs/secrets of CR
qliksense config usnet <servcie>
all of the above supports space separated multiple arguments
`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.UnsetCmd(args)
},
Args: cobra.MinimumNArgs(1),
}
return cmd
}

View File

@@ -1,46 +0,0 @@
package main
import (
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
var crdsCmd = &cobra.Command{
Use: "crds",
Short: "crds for qliksense and operators",
Long: `crds for qliksense and operators`,
}
func crdsViewCmd(q *qliksense.Qliksense) *cobra.Command {
opts := &qliksense.CrdCommandOptions{
All: true,
}
c := &cobra.Command{
Use: "view",
Short: "View CRDs for qliksense application. Use view --all=false to exclude the operator CRD",
Long: "View CRDs for qliksense application. Use view --all=false to exclude the operator CRD",
RunE: func(cmd *cobra.Command, args []string) error {
return q.ViewCrds(opts)
},
}
f := c.Flags()
f.BoolVarP(&opts.All, "all", "", opts.All, "If set to false, then the operator CRD is excluded")
return c
}
func crdsInstallCmd(q *qliksense.Qliksense) *cobra.Command {
opts := &qliksense.CrdCommandOptions{
All: true,
}
c := &cobra.Command{
Use: "install",
Short: "Install CRDs for Qliksense application. Use install --all=false to exclude the operator CRD",
Long: "Install CRDs for Qliksense application. Use install --all=false to exclude the operator CRD",
RunE: func(cmd *cobra.Command, args []string) error {
return q.InstallCrds(opts)
},
}
f := c.Flags()
f.BoolVarP(&opts.All, "all", "", opts.All, "If set to false, then the operator CRD is excluded")
return c
}

View File

@@ -1,109 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
"github.com/mattn/go-tty"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
type eulaPreRunHooksT struct {
validators map[string]func(cmd *cobra.Command, q *qliksense.Qliksense) (bool, error)
postValidationArtifacts map[string]interface{}
}
func (e *eulaPreRunHooksT) addValidator(command string, validator func(cmd *cobra.Command, q *qliksense.Qliksense) (bool, error)) {
e.validators[command] = validator
}
func (e *eulaPreRunHooksT) getValidator(command string) func(cmd *cobra.Command, q *qliksense.Qliksense) (bool, error) {
if validator, ok := e.validators[command]; ok {
return validator
}
return nil
}
func (e *eulaPreRunHooksT) addPostValidationArtifact(artifactName string, artifact interface{}) {
e.postValidationArtifacts[artifactName] = artifact
}
func (e *eulaPreRunHooksT) getPostValidationArtifact(artifactName string) interface{} {
if artifact, ok := e.postValidationArtifacts[artifactName]; ok {
return artifact
}
return nil
}
var eulaEnforced = os.Getenv("QLIKSENSE_EULA_ENFORCE") == "true"
var eulaText = "Please read the end user license agreement at: https://www.qlik.com/us/legal/license-terms"
var eulaPrompt = "Do you accept our EULA? (y/n): "
var eulaErrorInstruction = `You must enter "y" to continue or execute the command with the acceptEULA flag set to "yes"`
var eulaPreRunHooks = eulaPreRunHooksT{
validators: make(map[string]func(cmd *cobra.Command, q *qliksense.Qliksense) (bool, error)),
postValidationArtifacts: make(map[string]interface{}),
}
func commandAlwaysRequiresEulaAcceptance(commandName string) bool {
return commandName == fmt.Sprintf("%v install", rootCommandName) ||
commandName == fmt.Sprintf("%v apply", rootCommandName)
}
func globalEulaPreRun(cmd *cobra.Command, q *qliksense.Qliksense) {
if isEulaEnforced(cmd.CommandPath()) {
eulaFlagValue := strings.TrimSpace(strings.ToLower(cmd.Flag("acceptEULA").Value.String()))
if eulaFlagValue != "" && eulaFlagValue != "yes" {
doEnforceEula()
} else if eulaFlagValue == "" {
if eulaPreRunHook := eulaPreRunHooks.getValidator(cmd.CommandPath()); eulaPreRunHook != nil {
if eulaAccepted, err := eulaPreRunHook(cmd, q); err != nil {
panic(err)
} else if !eulaAccepted {
doEnforceEula()
}
} else if qConfig, err := qapi.NewQConfigE(q.QliksenseHome); err != nil {
doEnforceEula()
} else if qcr, err := qConfig.GetCurrentCR(); err != nil || !qcr.IsEULA() {
doEnforceEula()
}
}
}
}
func globalEulaPostRun(cmd *cobra.Command, q *qliksense.Qliksense) {
if isEulaEnforced(cmd.CommandPath()) {
if err := q.SetEulaAccepted(); err != nil {
panic(err)
}
}
}
func isEulaEnforced(commandName string) bool {
return eulaEnforced || commandAlwaysRequiresEulaAcceptance(commandName)
}
func doEnforceEula() {
fmt.Println(eulaText)
fmt.Print(eulaPrompt)
answer := readRuneFromTty()
if strings.ToLower(answer) != "y" {
fmt.Println(eulaErrorInstruction)
os.Exit(1)
}
}
func readRuneFromTty() string {
t, err := tty.Open()
if err != nil {
panic(err)
}
defer t.Close()
answer, err := t.ReadString()
if err != nil {
panic(err)
}
return answer
}

View File

@@ -1,30 +0,0 @@
package main
import (
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func fetchCmd(q *qliksense.Qliksense) *cobra.Command {
opts := &qliksense.FetchCommandOptions{}
c := &cobra.Command{
Use: "fetch",
Short: "fetch a release from qliksense-k8s repo, if version not supplied, will use from context",
Long: `fetch a release from qliksense-k8s repo, if version not supplied, will use from context`,
Example: `qliksense fetch [version]`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 1 {
opts.Version = args[0]
}
return q.FetchK8sWithOpts(opts)
},
}
f := c.Flags()
f.StringVarP(&opts.GitUrl, "url", "", "", "git url from where configuration will be pulled")
f.StringVarP(&opts.AccessToken, "accessToken", "", "", "access token for git url")
f.StringVarP(&opts.SecretName, "secretName", "", "", "kubernetes secret name where a key name accessToken exist")
f.BoolVarP(&opts.Overwrite, "overwrite", "", false, "Ovewrite previously fetched veersion as well as local chagnes")
return c
}

View File

@@ -1,29 +0,0 @@
package main
import (
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
const defaultVersionsLimit = 10
func getInstallableVersionsCmd(q *qliksense.Qliksense) *cobra.Command {
opts := &qliksense.LsRemoteCmdOptions{
IncludeBranches: false,
Limit: defaultVersionsLimit,
}
c := &cobra.Command{
Use: "get-versions",
Short: "list remote/installable versions",
Long: `list remote/installable versions`,
Example: `qliksense get-versions`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.GetInstallableVersions(opts)
},
}
f := c.Flags()
f.BoolVarP(&opts.IncludeBranches, "include-branches", "", opts.IncludeBranches, "Include branches")
f.IntVarP(&opts.Limit, "limit", "", opts.Limit, "Maximum versions to list (starting with the highest)")
return c
}

View File

@@ -1,97 +0,0 @@
package main
import (
"bytes"
"fmt"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func installCmd(q *qliksense.Qliksense) *cobra.Command {
opts := &qliksense.InstallCommandOptions{}
filePath := ""
keepPatchFiles, pull, push := false, false, false
c := &cobra.Command{
Use: "install",
Short: "install a qliksense release",
Long: `install a qliksense release`,
Example: `qliksense install <version> #if no version provides, expect manifestsRoot is set somewhere in the file system
# qliksense install -f file_name or cat cr_file | qliksense install -f -
`,
RunE: func(cmd *cobra.Command, args []string) error {
if filePath != "" {
return runLoadOrApplyCommandE(cmd, func(crBytes []byte) error {
if cr, crBytesWithEula, err := getCrWithEulaInserted(crBytes); err != nil {
return err
} else if err := validatePullPushFlagsOnApply(cr, pull, push); err != nil {
return err
} else {
return q.ApplyCRFromReader(bytes.NewReader(crBytesWithEula), opts, keepPatchFiles, true, pull, push)
}
})
} else {
version := ""
if len(args) != 0 {
version = args[0]
}
if err := validatePullPushFlagsOnInstall(q, pull, push); err != nil {
return err
}
if pull {
fmt.Println("Pulling images...")
if err := q.PullImages(version, ""); err != nil {
return err
}
}
if push {
fmt.Println("Pushing images...")
if err := q.PushImagesForCurrentCR(); err != nil {
return err
}
}
return q.InstallQK8s(version, opts, keepPatchFiles)
}
},
}
eulaPreRunHooks.addValidator(fmt.Sprintf("%v %v", rootCommandName, c.Name()), func(cmd *cobra.Command, q *qliksense.Qliksense) (b bool, err error) {
if filePath != "" {
return loadOrApplyCommandEulaPreRunHook(cmd, q)
} else if qConfig, err := qapi.NewQConfigE(q.QliksenseHome); err != nil {
return false, nil
} else if qcr, err := qConfig.GetCurrentCR(); err != nil {
return false, nil
} else {
return qcr.IsEULA(), nil
}
})
f := c.Flags()
f.StringVarP(&opts.StorageClass, "storageClass", "s", "", "Storage class for qliksense")
f.StringVarP(&opts.MongodbUri, "mongodbUri", "m", "", "mongodbUri for qliksense (i.e. mongodb://qlik-default-mongodb:27017/qliksense?ssl=false)")
f.StringVarP(&opts.RotateKeys, "rotateKeys", "r", "", "Rotate JWT keys for qliksense (yes:rotate keys/ no:use exising keys from cluster/ None: use default EJSON_KEY from env")
f.BoolVar(&keepPatchFiles, keepPatchFilesFlagName, keepPatchFiles, keepPatchFilesFlagUsage)
f.StringVarP(&filePath, "file", "f", "", "Install from a CR file")
f.BoolVarP(&opts.DryRun, "dry-run", "", false, "Dry run will generate the patches without rotating keys")
f.BoolVarP(&pull, pullFlagName, pullFlagShorthand, pull, pullFlagUsage)
f.BoolVarP(&push, pushFlagName, pushFlagShorthand, push, pushFlagUsage)
return c
}
func validatePullPushFlagsOnInstall(q *qliksense.Qliksense, pull, push bool) error {
if pull && !push {
fmt.Printf("WARNING: pulling images without pushing them")
}
if push {
if err := ensureImageRegistrySetInCR(q); err != nil {
return err
}
}
return nil
}

View File

@@ -1,88 +0,0 @@
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"github.com/pkg/errors"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func loadCrFile(q *qliksense.Qliksense) *cobra.Command {
filePath := ""
overwriteExistingContext := false
c := &cobra.Command{
Use: "load",
Short: "load a CR a file and create necessary structure for future use",
Long: `load a CR a file and create necessary structure for future use`,
Example: `qliksense load -f file_name or cat cr_file | qliksense load -f -`,
RunE: func(cmd *cobra.Command, args []string) error {
return runLoadOrApplyCommandE(cmd, func(buffer []byte) error {
return q.LoadCr(bytes.NewReader(buffer), overwriteExistingContext)
})
},
}
f := c.Flags()
f.StringVarP(&filePath, "file", "f", "", "File to load CR from")
c.MarkFlagRequired("file")
f.BoolVarP(&overwriteExistingContext, "overwrite", "o", overwriteExistingContext, "Overwrite any existing contexts with the same name")
eulaPreRunHooks.addValidator(fmt.Sprintf("%v %v", rootCommandName, c.Name()), loadOrApplyCommandEulaPreRunHook)
return c
}
func getCrFileFromFlag(cmd *cobra.Command, flagName string) (*os.File, error) {
filePath := cmd.Flag(flagName).Value.String()
if filePath == "-" {
if !isInputFromPipe() {
return nil, errors.New("No input pipe present")
}
return os.Stdin, nil
}
file, e := os.Open(filePath)
if e != nil {
return nil, errors.Wrapf(e,
"unable to read the file %s", filePath)
}
return file, nil
}
func isInputFromPipe() bool {
fileInfo, _ := os.Stdin.Stat()
return fileInfo.Mode()&os.ModeCharDevice == 0
}
func loadOrApplyCommandEulaPreRunHook(cmd *cobra.Command, q *qliksense.Qliksense) (bool, error) {
file, err := getCrFileFromFlag(cmd, "file")
if err != nil {
return false, err
}
defer file.Close()
if crBytes, err := ioutil.ReadAll(file); err != nil {
return false, err
} else {
eulaPreRunHooks.addPostValidationArtifact("CR", crBytes)
return q.IsEulaAcceptedInCrFile(bytes.NewBuffer(crBytes))
}
}
func runLoadOrApplyCommandE(cmd *cobra.Command, callBack func(buffer []byte) error) error {
if crBytes := eulaPreRunHooks.getPostValidationArtifact("CR"); crBytes != nil {
return callBack(crBytes.([]byte))
} else {
file, err := getCrFileFromFlag(cmd, "file")
if err != nil {
return err
}
defer file.Close()
if crBytes, err := ioutil.ReadAll(file); err != nil {
return err
} else {
return callBack(crBytes)
}
}
}

View File

@@ -1,50 +0,0 @@
package main
import (
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
var operatorCmd = &cobra.Command{
Use: "operator",
Short: "Configuration for operator",
Long: `Configuration for operator`,
}
/*
func operatorViewCmd(q *qliksense.Qliksense) *cobra.Command {
c := &cobra.Command{
Use: "view",
Short: "View CRD for operator",
Long: `View CRD for operator`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.ViewOperator()
},
}
return c
}
*/
func operatorCrdCmd(q *qliksense.Qliksense) *cobra.Command {
c := &cobra.Command{
Use: "crd",
Short: "View CRD for operator",
Long: `View CRD for operator`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.ViewOperator()
},
}
return c
}
func operatorControllerCmd(q *qliksense.Qliksense) *cobra.Command {
c := &cobra.Command{
Use: "controller",
Short: "View manifests for operator controller",
Long: `View manifests for operator controller`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.ViewOperatorController()
},
}
return c
}

31
cmd/qliksense/porter.go Normal file
View File

@@ -0,0 +1,31 @@
package main
import (
"fmt"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
"strings"
)
func porter(q *qliksense.Qliksense) *cobra.Command {
return &cobra.Command{
Use: "porter",
Short: "Execute a porter command",
DisableFlagParsing: true,
RunE: func(cobCmd *cobra.Command, args []string) error {
var (
err error
)
if _, err = q.CallPorter(args,
func(x string) (out *string) {
out = new(string)
*out = strings.ReplaceAll(x, "porter", "qliksense porter")
fmt.Println(*out)
return
}); err != nil {
return err
}
return nil
},
}
}

View File

@@ -1,60 +0,0 @@
package main
import (
"fmt"
. "github.com/logrusorgru/aurora"
ansi "github.com/mattn/go-colorable"
"github.com/qlik-oss/sense-installer/pkg/api"
postflight "github.com/qlik-oss/sense-installer/pkg/postflight"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func postflightCmd(q *qliksense.Qliksense) *cobra.Command {
postflightOpts := &postflight.PostflightOptions{}
var postflightCmd = &cobra.Command{
Use: "postflight",
Short: "perform postflight checks on the cluster",
Long: `perform postflight checks on the cluster`,
Example: `qliksense postflight <postflight_check_to_run>`,
}
f := postflightCmd.Flags()
f.BoolVarP(&postflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return postflightCmd
}
func pfMigrationCheck(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
postflightOpts := &postflight.PostflightOptions{}
var postflightMigrationCmd = &cobra.Command{
Use: "db-migration-check",
Short: "check mongodb migration status on the cluster",
Long: `check mongodb migration status on the cluster`,
Example: `qliksense postflight db-migration-check`,
RunE: func(cmd *cobra.Command, args []string) error {
pf := &postflight.QliksensePostflight{Q: q, P: postflightOpts, CG: &api.ClientGoUtils{Verbose: postflightOpts.Verbose}}
// Postflight db_migration_check
namespace, kubeConfigContents, err := pf.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Postflight db_migration_check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if namespace == "" {
namespace = "default"
}
if err = pf.DbMigrationCheck(namespace, kubeConfigContents); err != nil {
fmt.Fprintf(out, "%s\n", Red("Postflight db_migration_check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Postflight db_migration_check completed"))
return nil
},
}
f := postflightMigrationCmd.Flags()
f.BoolVarP(&postflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return postflightMigrationCmd
}

View File

@@ -1,474 +0,0 @@
package main
import (
"fmt"
. "github.com/logrusorgru/aurora"
ansi "github.com/mattn/go-colorable"
"github.com/qlik-oss/sense-installer/pkg/api"
"github.com/qlik-oss/sense-installer/pkg/preflight"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func preflightCmd(q *qliksense.Qliksense) *cobra.Command {
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var preflightCmd = &cobra.Command{
Use: "preflight",
Short: "perform preflight checks on the cluster",
Long: `perform preflight checks on the cluster`,
Example: `qliksense preflight <preflight_check_to_run>`,
}
f := preflightCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return preflightCmd
}
func pfDnsCheckCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var preflightDnsCmd = &cobra.Command{
Use: "dns",
Short: "perform preflight dns check",
Long: `perform preflight dns check to check DNS connectivity status in the cluster`,
Example: `qliksense preflight dns`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight DNS check
namespace, kubeConfigContents, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight DNS check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if namespace == "" {
namespace = "default"
}
if err = qp.CheckDns(namespace, kubeConfigContents, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight DNS check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight DNS check PASSED"))
return nil
},
}
f := preflightDnsCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return preflightDnsCmd
}
func pfK8sVersionCheckCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var preflightCheckK8sVersionCmd = &cobra.Command{
Use: "k8s-version",
Short: "check kubernetes version",
Long: `check minimum valid kubernetes version on the cluster`,
Example: `qliksense preflight k8s-version`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight Kubernetes minimum version check
namespace, kubeConfigContents, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight kubernetes minimum version check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if err = qp.CheckK8sVersion(namespace, kubeConfigContents); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight kubernetes minimum version check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight kubernetes minimum version check PASSED"))
return nil
},
}
f := preflightCheckK8sVersionCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return preflightCheckK8sVersionCmd
}
func pfAllChecksCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var preflightAllChecksCmd = &cobra.Command{
Use: "all",
Short: "perform all checks",
Long: `perform all preflight checks on the target cluster`,
Example: `qliksense preflight all`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight run all checks
fmt.Printf("Running all preflight checks...\n\n")
namespace, kubeConfigContents, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Unable to run the preflight checks suite"))
fmt.Printf("Error: %v\n", err)
return nil
}
if namespace == "" {
namespace = "default"
}
if err = qp.RunAllPreflightChecks(kubeConfigContents, namespace, preflightOpts); err != nil {
fmt.Fprintf(out, "%s\n", Red("1 or more preflight checks have FAILED"))
fmt.Println("Completed running all preflight checks")
return nil
}
fmt.Fprintf(out, "%s\n\n", Green("All preflight checks have PASSED"))
return nil
},
}
f := preflightAllChecksCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
f.StringVarP(&preflightOpts.MongoOptions.MongodbUrl, "mongodb-url", "", "", "mongodbUrl to try connecting to")
f.StringVarP(&preflightOpts.MongoOptions.CaCertFile, "mongodb-ca-cert", "", "", "certificate to use for mongodb check")
return preflightAllChecksCmd
}
func pfDeploymentCheckCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var pfDeploymentCheckCmd = &cobra.Command{
Use: "deployment",
Short: "perform preflight deployment check",
Long: `perform preflight deployment check to ensure that we can create deployments in the cluster`,
Example: `qliksense preflight deployment`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight deployments check
namespace, kubeConfigContents, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight deployment check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if namespace == "" {
namespace = "default"
}
if err = qp.CheckDeployment(namespace, kubeConfigContents, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight deployment check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight deployment check PASSED"))
return nil
},
}
f := pfDeploymentCheckCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return pfDeploymentCheckCmd
}
func pfServiceCheckCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var pfServiceCheckCmd = &cobra.Command{
Use: "service",
Short: "perform preflight service check",
Long: `perform preflight service check to ensure that we are able to create services in the cluster`,
Example: `qliksense preflight service`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight service check
namespace, kubeConfigContents, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight service check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if namespace == "" {
namespace = "default"
}
if err = qp.CheckService(namespace, kubeConfigContents, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight service check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight service check PASSED"))
return nil
},
}
f := pfServiceCheckCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return pfServiceCheckCmd
}
func pfPodCheckCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var pfPodCheckCmd = &cobra.Command{
Use: "pod",
Short: "perform preflight pod check",
Long: `perform preflight pod check to ensure we can create pods in the cluster`,
Example: `qliksense preflight pod`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight pod check
namespace, kubeConfigContents, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight pod check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if namespace == "" {
namespace = "default"
}
if err = qp.CheckPod(namespace, kubeConfigContents, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight pod check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight pod check PASSED"))
return nil
},
}
f := pfPodCheckCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return pfPodCheckCmd
}
func pfCreateRoleCheckCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var preflightRoleCmd = &cobra.Command{
Use: "role",
Short: "preflight create role check",
Long: `perform preflight role check to ensure we are able to create a role in the cluster`,
Example: `qliksense preflight createRole`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight role check
namespace, _, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight role check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if err = qp.CheckCreateRole(namespace, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight role check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight role check PASSED"))
return nil
},
}
f := preflightRoleCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return preflightRoleCmd
}
func pfCreateRoleBindingCheckCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var preflightRoleBindingCmd = &cobra.Command{
Use: "rolebinding",
Short: "preflight create rolebinding check",
Long: `perform preflight rolebinding check to ensure we are able to create a rolebinding in the cluster`,
Example: `qliksense preflight rolebinding`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight createRoleBinding check
namespace, _, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight rolebinding check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if err = qp.CheckCreateRoleBinding(namespace, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight rolebinding check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight rolebinding check PASSED"))
return nil
},
}
f := preflightRoleBindingCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return preflightRoleBindingCmd
}
func pfCreateServiceAccountCheckCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var preflightServiceAccountCmd = &cobra.Command{
Use: "serviceaccount",
Short: "preflight create serviceaccount check",
Long: `perform preflight serviceaccount check to ensure we are able to create a service account in the cluster`,
Example: `qliksense preflight serviceaccount`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight createServiceAccount check
namespace, _, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight ServiceAccount check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if err = qp.CheckCreateServiceAccount(namespace, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight ServiceAccount check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight ServiceAccount check PASSED"))
return nil
},
}
f := preflightServiceAccountCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return preflightServiceAccountCmd
}
func pfCreateAuthCheckCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var preflightCreateAuthCmd = &cobra.Command{
Use: "authcheck",
Short: "preflight authcheck",
Long: `perform preflight authcheck that combines the role, rolebinding and serviceaccount checks`,
Example: `qliksense preflight authcheck`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight authcheck
namespace, kubeConfigContents, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight authcheck FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if err = qp.CheckCreateRB(namespace, kubeConfigContents); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight authcheck FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight authcheck PASSED"))
return nil
},
}
f := preflightCreateAuthCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return preflightCreateAuthCmd
}
func pfMongoCheckCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var preflightMongoCmd = &cobra.Command{
Use: "mongo",
Short: "preflight mongo OR preflight mongo --url=<url>",
Long: `perform preflight mongo check to ensure we are able to connect to a mongodb instance in the cluster`,
Example: `qliksense preflight mongo OR preflight mongo --url=<url>`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight mongo check
namespace, kubeConfigContents, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight mongo check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if namespace == "" {
namespace = "default"
}
if err = qp.CheckMongo(kubeConfigContents, namespace, preflightOpts, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight mongo check FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight mongo check PASSED"))
return nil
},
}
f := preflightMongoCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
f.StringVarP(&preflightOpts.MongoOptions.MongodbUrl, "url", "", "", "mongodbUrl to try connecting to")
f.StringVarP(&preflightOpts.MongoOptions.CaCertFile, "ca-cert", "", "", "ca certificate to use for mongodb check")
return preflightMongoCmd
}
func pfCleanupCmd(q *qliksense.Qliksense) *cobra.Command {
out := ansi.NewColorableStdout()
preflightOpts := &preflight.PreflightOptions{
MongoOptions: &preflight.MongoOptions{},
}
var pfCleanCmd = &cobra.Command{
Use: "clean",
Short: "perform preflight clean",
Long: `perform preflight clean to ensure that all resources are cleared up in the cluster`,
Example: `qliksense preflight clean`,
RunE: func(cmd *cobra.Command, args []string) error {
qp := &preflight.QliksensePreflight{Q: q, P: preflightOpts, CG: &api.ClientGoUtils{Verbose: preflightOpts.Verbose}}
// Preflight clean
namespace, kubeConfigContents, err := qp.CG.LoadKubeConfigAndNamespace()
if err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight cleanup FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
if namespace == "" {
namespace = "default"
}
if err = qp.Cleanup(namespace, kubeConfigContents); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight cleanup FAILED"))
fmt.Printf("Error: %v\n", err)
return nil
}
fmt.Fprintf(out, "%s\n", Green("Preflight cleanup complete"))
return nil
},
}
f := pfCleanCmd.Flags()
f.BoolVarP(&preflightOpts.Verbose, "verbose", "v", false, "verbose mode")
return pfCleanCmd
}

33
cmd/qliksense/pull.go Normal file
View File

@@ -0,0 +1,33 @@
package main
import (
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func pullQliksenseImages(q *qliksense.Qliksense) *cobra.Command {
var (
cmd *cobra.Command
opts *aboutOptions
)
opts = &aboutOptions{}
cmd = &cobra.Command{
Use: "pull",
Short: "Pull docke images for offline install",
Example: `qliksense pull`,
RunE: func(cmd *cobra.Command, args []string) error {
return q.PullImages(opts.getTagDefaults(args))
},
}
f := cmd.Flags()
f.StringVarP(&opts.Version, "version", "v", "latest",
"From version of Qlik Sense The images will be pulled")
f.StringVarP(&opts.Tag, "tag", "t", "",
"Use a bundle in an OCI registry specified by the given tag")
f.StringVarP(&opts.File, "file", "f", "",
"Path to the porter manifest file. Defaults to the bundle in the current directory.")
f.StringVar(&opts.CNABFile, "cnab-file", "",
"Path to the CNAB bundle.json file.")
return cmd
}

View File

@@ -1,55 +0,0 @@
package main
import (
"errors"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func pullQliksenseImages(q *qliksense.Qliksense) *cobra.Command {
opts := &aboutCommandOptions{}
cmd := &cobra.Command{
Use: "pull",
Short: "Pull docker images for offline install",
Example: `qliksense pull`,
RunE: func(cmd *cobra.Command, args []string) error {
version, err := getSingleArg(args)
if err != nil {
return err
}
return q.PullImages(version, opts.Profile)
},
}
f := cmd.Flags()
f.StringVar(&opts.Profile, "profile", "", "Configuration profile")
return cmd
}
func pushQliksenseImages(q *qliksense.Qliksense) *cobra.Command {
cmd := &cobra.Command{
Use: "push",
Short: "Push docker images for offline install",
Example: `qliksense push`,
RunE: func(cmd *cobra.Command, args []string) error {
if err := ensureImageRegistrySetInCR(q); err != nil {
return err
} else {
return q.PushImagesForCurrentCR()
}
},
}
return cmd
}
func ensureImageRegistrySetInCR(q *qliksense.Qliksense) error {
qConfig := qapi.NewQConfig(q.QliksenseHome)
if qcr, err := qConfig.GetCurrentCR(); err != nil {
return err
} else if registry := qcr.Spec.GetImageRegistry(); registry == "" {
return errors.New("no image registry set in the CR; to set it use: qliksense config set-image-registry")
}
return nil
}

View File

@@ -3,68 +3,71 @@ package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
. "github.com/logrusorgru/aurora"
ansi "github.com/mattn/go-colorable"
"github.com/mitchellh/go-homedir"
"github.com/qlik-oss/sense-installer/pkg"
"github.com/qlik-oss/sense-installer/pkg/api"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// To run this project in debug mode, run:
// export QLIKSENSE_DEBUG=true
// qliksense <command>
const (
qlikSenseHomeVar = "QLIKSENSE_HOME"
qlikSenseDirVar = ".qliksense"
keepPatchFilesFlagName = "keep-config-repo-patches"
keepPatchFilesFlagUsage = "Keep config repo patch files (for debugging)"
pullFlagName = "pull"
pullFlagShorthand = "d"
pullFlagUsage = "If using private docker registry, pull (download) all required Qliksense images before install"
pushFlagName = "push"
pushFlagShorthand = "u"
pushFlagUsage = "If using private docker registry, push (upload) all downloaded Qliksense images to that registry before install"
rootCommandName = "qliksense"
// porterURLBase = "https://deislabs.blob.core.windows.net/porter"
porterURLBase = "https://github.com/qlik-oss/sense-installer/releases/download"
porterHomeVar = "PORTER_HOME"
qlikSenseHomeVar = "QLIKSENSE_HOME"
qlikSenseDirVar = ".qliksense"
mixinDirVar = "mixins"
porterRuntime = "porter-runtime"
)
func initAndExecute() error {
var (
qlikSenseHome string
err error
porterExe string
err error
)
qlikSenseHome, err = setUpPaths()
if err != nil {
log.Fatal(err)
if porterExe, err = installPorter(); err != nil {
return err
}
// create dirs and appropriate files for setting up contexts
api.LogDebugMessage("QliksenseHomeDir: %s\n", qlikSenseHome)
qliksenseClient := qliksense.New(qlikSenseHome)
cmd := rootCmd(qliksenseClient)
if err := cmd.Execute(); err != nil {
//levenstein checks (auto-suggestions)
levenstein(cmd)
if err := rootCmd(qliksense.New(porterExe)).Execute(); err != nil {
return err
}
return nil
}
func setUpPaths() (string, error) {
func installPorter() (string, error) {
var (
homeDir, qlikSenseHome string
err error
porterPermaLink = pkg.Version
//porterPermaLink = "v0.3.0"
destination, homeDir, mixin, mixinOpts, qlikSenseHome, porterExe, ext string
mixinsVar = map[string]string{
"kustomize": "-v 0.2-beta-3-0e19ca4 --url https://github.com/donmstewart/porter-kustomize/releases/download",
"qliksense": "-v v0.14.0 --url https://github.com/qlik-oss/porter-qliksense/releases/download",
"exec": "-v latest",
"kubernetes": "-v latest",
"helm": "-v latest",
"azure": "-v latest",
"terraform": "-v latest",
"az": "-v latest",
"aws": "-v latest",
"gcloud": "-v latest",
}
downloadMixins map[string]string
downloadPorter bool
err error
cmd *exec.Cmd
)
porterExe = "porter"
if runtime.GOOS == "windows" {
porterExe = porterExe + ".exe"
}
if qlikSenseHome = os.Getenv(qlikSenseHomeVar); qlikSenseHome == "" {
if homeDir, err = homedir.Dir(); err != nil {
return "", err
@@ -74,66 +77,116 @@ func setUpPaths() (string, error) {
}
qlikSenseHome = filepath.Join(homeDir, qlikSenseDirVar)
}
if err := os.MkdirAll(qlikSenseHome, os.ModePerm); err != nil {
return "", err
os.Setenv(porterHomeVar, qlikSenseHome)
//TODO: Check if porter version is one alreadu is one for this build
porterExe = filepath.Join(qlikSenseHome, porterExe)
if _, err = os.Stat(qlikSenseHome); err != nil {
if os.IsNotExist(err) {
downloadPorter = true
} else {
return "", err
}
} else {
if _, err = os.Stat(porterExe); err != nil {
if os.IsNotExist(err) {
downloadPorter = true
} else {
return "", err
}
}
}
if downloadPorter {
os.Mkdir(qlikSenseHome, os.ModePerm)
destination = filepath.Join(qlikSenseHome, porterRuntime)
if err = downloadFile(porterURLBase+"/"+porterPermaLink+"/porter-linux-amd64", destination); err != nil {
return "", err
}
os.Chmod(destination, 0755)
if runtime.GOOS == "linux" && runtime.GOARCH == "amd64" {
if _, err = copy(filepath.Join(qlikSenseHome, porterRuntime), porterExe); err != nil {
return "", err
}
os.Chmod(porterExe, 0755)
} else {
if runtime.GOOS == "windows" {
ext = ".exe"
}
if err = downloadFile(porterURLBase+"/"+porterPermaLink+"/"+"porter-"+runtime.GOOS+"-"+runtime.GOARCH+ext, porterExe); err != nil {
return "", err
}
os.Chmod(porterExe, 0755)
}
}
return qlikSenseHome, nil
if _, err = os.Stat(filepath.Join(qlikSenseHome, mixinDirVar)); err != nil {
if os.IsNotExist(err) {
downloadMixins = mixinsVar
} else {
return "", err
}
} else {
downloadMixins = make(map[string]string)
for mixin, mixinOpts = range mixinsVar {
if _, err = os.Stat(filepath.Join(qlikSenseHome, mixinDirVar, mixin)); err != nil {
if os.IsNotExist(err) {
downloadMixins[mixin] = mixinOpts
} else {
return "", err
}
}
}
}
for mixin, mixinOpts = range downloadMixins {
cmd = exec.Command(porterExe, append([]string{"mixin", "install", mixin}, strings.Split(mixinOpts, " ")...)...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
return "", err
}
}
return porterExe, nil
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of qliksense cli",
Long: "Print the version number of qliksense cli",
Long: `All software has versions. This is Hugo's`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("%s (%s, %s)\n", pkg.Version, pkg.Commit, pkg.CommitDate)
},
}
func commandUsesContext(commandName string) bool {
return commandName != "" &&
commandName != rootCommandName &&
commandName != fmt.Sprintf("%v help", rootCommandName) &&
commandName != fmt.Sprintf("%v version", rootCommandName)
}
func rootCmd(p *qliksense.Qliksense) *cobra.Command {
var (
cmd, porterCmd, alias *cobra.Command
)
func getRootCmd(p *qliksense.Qliksense) *cobra.Command {
cmd := &cobra.Command{
Use: rootCommandName,
cmd = &cobra.Command{
Use: "qliksense",
Short: "Qliksense cli tool",
Long: `qliksense cli tool provides functionality to perform operations on qliksense-k8s, qliksense operator, and kubernetes cluster`,
Args: cobra.ArbitraryArgs,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if commandUsesContext(cmd.CommandPath()) {
globalEulaPreRun(cmd, p)
if err := p.SetUpQliksenseDefaultContext(); err != nil {
panic(err)
}
pf := api.NewPreflightConfig(p.QliksenseHome)
if err := pf.Initialize(); err != nil {
panic(err)
}
globalEulaPostRun(cmd, p)
}
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
if commandUsesContext(cmd.CommandPath()) {
globalEulaPostRun(cmd, p)
}
},
Long: `qliksense cli tool provides a wrapper around the porter api as well as
provides addition functionality`,
Args: cobra.ArbitraryArgs,
SilenceUsage: true,
}
origHelpFunc := cmd.HelpFunc()
cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
if !commandUsesContext(cmd.CommandPath()) {
cmd.Flags().MarkHidden("acceptEULA")
}
origHelpFunc(cmd, args)
})
accept := ""
cmd.PersistentFlags().StringVarP(&accept, "acceptEULA", "a", "", "Accept EULA for qliksense")
cmd.Flags().SetInterspersed(false)
cobra.OnInitialize(initConfig)
// For qliksense overrides/commands
cmd.AddCommand(pullQliksenseImages(p))
porterCmd = porter(p)
cmd.AddCommand(porterCmd)
for _, alias = range buildAliasCommands(porterCmd, p) {
cmd.AddCommand(alias)
}
// add version command
cmd.AddCommand(versionCmd)
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
return cmd
}
@@ -142,100 +195,30 @@ func initConfig() {
viper.AutomaticEnv()
}
func rootCmd(p *qliksense.Qliksense) *cobra.Command {
cmd := getRootCmd(p)
cobra.OnInitialize(initConfig)
func downloadFile(url string, filepath string) error {
var (
out *os.File
err error
resp *http.Response
)
// Create the file
if out, err = os.Create(filepath); err != nil {
return err
}
defer out.Close()
cmd.AddCommand(getInstallableVersionsCmd(p))
cmd.AddCommand(pullQliksenseImages(p))
cmd.AddCommand(pushQliksenseImages(p))
cmd.AddCommand(about(p))
// add version command
cmd.AddCommand(versionCmd)
// Get the data
if resp, err = http.Get(url); err != nil {
return err
}
defer resp.Body.Close()
// add operator command
cmd.AddCommand(operatorCmd)
//operatorCmd.AddCommand(operatorViewCmd(p))
operatorCmd.AddCommand(operatorCrdCmd(p))
operatorCmd.AddCommand(operatorControllerCmd(p))
// Write the body to file
if _, err = io.Copy(out, resp.Body); err != nil {
return err
}
//add fetch command
cmd.AddCommand(fetchCmd(p))
// add install command
cmd.AddCommand(installCmd(p))
// add config command
configCmd := configCmd(p)
cmd.AddCommand(configCmd)
configCmd.AddCommand(configApplyCmd(p))
configCmd.AddCommand(configViewCmd(p))
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
// add the set-context config command as a sub-command to the app config command
configCmd.AddCommand(setContextConfigCmd(p))
// add the set profile/namespace/storageClassName/git-repository config command as a sub-command to the app config command
configCmd.AddCommand(setOtherConfigsCmd(p))
// add the set ### config command as a sub-command to the app config sub-command
configCmd.AddCommand(setConfigsCmd(p))
// add the set ### config command as a sub-command to the app config sub-command
configCmd.AddCommand(setSecretsCmd(p))
// add the list config command as a sub-command to the app config sub-command
configCmd.AddCommand(listContextConfigCmd(p))
// add the delete-context config command as a sub-command to the app config command
configCmd.AddCommand(deleteContextConfigCmd(p))
// add set-image-registry command as a sub-command to the app config sub-command
configCmd.AddCommand(setImageRegistryCmd(p))
// add clean-config-repo-patches command as a sub-command to the app config sub-command
configCmd.AddCommand(cleanConfigRepoPatchesCmd(p))
// open editor for config
configCmd.AddCommand(configEditCmd(p))
// add unset for config
configCmd.AddCommand((unsetCmd(p)))
// add uninstall command
cmd.AddCommand(uninstallCmd(p))
// add crds
cmd.AddCommand(crdsCmd)
crdsCmd.AddCommand(crdsViewCmd(p))
crdsCmd.AddCommand(crdsInstallCmd(p))
// add preflight commands
preflightCmd := preflightCmd(p)
preflightCmd.AddCommand(pfDnsCheckCmd(p))
preflightCmd.AddCommand(pfK8sVersionCheckCmd(p))
preflightCmd.AddCommand(pfAllChecksCmd(p))
preflightCmd.AddCommand(pfMongoCheckCmd(p))
preflightCmd.AddCommand(pfDeploymentCheckCmd(p))
preflightCmd.AddCommand(pfServiceCheckCmd(p))
preflightCmd.AddCommand(pfPodCheckCmd(p))
preflightCmd.AddCommand(pfCreateRoleCheckCmd(p))
preflightCmd.AddCommand(pfCreateRoleBindingCheckCmd(p))
preflightCmd.AddCommand(pfCreateServiceAccountCheckCmd(p))
preflightCmd.AddCommand(pfCreateAuthCheckCmd(p))
preflightCmd.AddCommand(pfCleanupCmd(p))
cmd.AddCommand(preflightCmd)
cmd.AddCommand(loadCrFile(p))
cmd.AddCommand((applyCmd(p)))
// add postflight command
postflightCmd := postflightCmd(p)
postflightCmd.AddCommand(pfMigrationCheck(p))
cmd.AddCommand(postflightCmd)
return cmd
return nil
}
func copy(src, dst string) (int64, error) {
@@ -265,22 +248,3 @@ func copy(src, dst string) (int64, error) {
nBytes, err = io.Copy(destination, source)
return nBytes, err
}
func levenstein(cmd *cobra.Command) {
cmd.SuggestionsMinimumDistance = 2
if len(os.Args) > 1 {
args := os.Args[1]
suggest := cmd.SuggestionsFor(args)
if len(suggest) > 0 {
arg := []string{}
for _, cm := range os.Args {
arg = append(arg, cm)
}
if !strings.EqualFold(arg[1], suggest[0]) {
arg[1] = suggest[0]
out := ansi.NewColorableStdout()
fmt.Fprintln(out, Green("Did you mean: "), Bold(strings.Join(arg, " ")), "?")
}
}
}
}

View File

@@ -1,28 +0,0 @@
package main
import (
"github.com/qlik-oss/sense-installer/pkg/qliksense"
"github.com/spf13/cobra"
)
func uninstallCmd(q *qliksense.Qliksense) *cobra.Command {
skipConfirmation := false
c := &cobra.Command{
Use: "uninstall",
Short: "Uninstall the deployed qliksense.",
Long: `Uninstall the deployed qliksense. By default uninstall the current context`,
Example: `qliksense uninstall <context-name>`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return q.UninstallQK8s(args[0], skipConfirmation)
}
return q.UninstallQK8s("", skipConfirmation)
},
}
f := c.Flags()
f.BoolVar(&skipConfirmation, "yes", skipConfirmation, "skips confirmation")
return c
}

View File

View File

@@ -1,159 +0,0 @@
# CLI reference
### qliksense preflight
Preflight checks provide pre-installation cluster conformance testing and validation before we install qliksense on the cluster. We gather a suite of conformance tests that can be easily written and run on the target cluster to verify that cluster-specific requirements are met.
We support a couple of tests at the moment as part of preflight checks, and the range of the suite will be expanded in future.
Run the following command to view help about the commands supported by preflight at any moment:
```
qliksense preflight
```
#### Running all checks
Run the following command to execute all preflight checks
```
qliksense preflight all --mongodb-url=<mongo-server url> --mongodb-ca-cert=<path to ca-cert file>
```
#### Running specific check
Run the following command to execute a specific check
```
qliksense preflight dns
```
#### Running cleanup
Run the following command to cleanup entities created for preflight checks that were left behind on the cluster.
```
qliksense preflight clean
```
### qliksense postflight
Postflight checks are performed after qliksense is installed on the cluster and during normal operating mode of the product. Such checks can range from validating certain conditions to checking the status of certain operations or entities.
Run the following command to view help about the commands supported by postflight at any moment:
```
qliksense postflight
```
### qliksense load
`qliksense load` command takes input from a file or from pipe
- `qliksense load -f cr-file.yaml`
- `cat cr-file.yaml | qliksense load -f -`
This will load the Custom Resource (CR) into `${QLIKSENSE_HOME}` folder, create context structure and set the current context to that CR.
This will also encrypt the secrets from CR while writing the CR into the disk.
### qliksense apply
`qliksense apply` command takes input from a file or from pipe
- `qliksense apply -f cr-file.yaml`
- `cat cr-file.yaml | qliksense apply -f -`
The content of `cr-file.yaml` should be something like the following:
```yaml
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-test
labels:
version: v0.0.2
spec:
configs:
qliksense:
- name: acceptEULA
value: "yes"
secrets:
qliksense:
- name: mongodbUri
value: mongodb://qlik-test-mongodb:27017/qliksense?ssl=false
profile: docker-desktop
rotateKeys: "yes"
```
`qliksense apply` does everything `qliksense load` does but will install Qlik Sense into the cluster as well
### qliksense about
`qliksense about` command will display information about [qliksense-k8s](https://github.com/qlik-oss/qliksense-k8s) release.
For example, running the following command will show information about default profile for `1.0.0` tag
```
qliksense about 1.0.0
```
Run the following command to view options for `about` command:
```
qliksense about --help
```
Using other supported commands user might have built the CR into the location `~/.qliksense/myqliksense.yaml`
```yaml
apiVersion: qlik.com/v1
kind: QlikSense
metadata:
name: myqliksense
spec:
profile: docker-desktop
manifestsRoot: /Usr/xyz/my-k8-repo/manifests
namespace: myqliksense
storageClassName: efs
configs:
qliksense:
- name: acceptEULA
value: "yes"
secrets:
qliksense:
- name: mongodbUri
value: "mongo://mongo:3307"
- name: messagingPassword
valueFromKey: messagingPassword
```
In this case, the result of `qliksense about` command would display information from:
- `/Usr/xyz/my-k8-repo/manifests/docker-desktop` location, or
- Pull and show information from `master` branch if the directory is invalid or empty
### qliksense config
`qliksense config` will perform operations on configurations and contexts regarding the [qliksense-k8](https://github.com/qlik-oss/qliksense-k8s) release.
It supports the following flags:
- `qliksense config apply` - generate the patches and apply manifests to K8s
- `qliksense config list-contexts` - get and list contexts
- `qliksense config set` - configure a key-value pair into the current context
- `qliksense config set-configs` - set configurations into qliksense context as key-value pairs
- `qliksense config set-context` - sets the Kubernetes context where resources are located
- `qliksense config set-secrets <service_name>.<attribute>="<value>" --secret=false` - set secrets configurations into qliksense context as key-value pairs and show encrypted value as part of CR
- `qliksense config set-secrets <service_name>.<attribute>="<value>" --secret=true` - set secrets configurations into qliksense context as key-value pairs and show a key reference to the created Kubernetes secret resource as part of the CR
- `qliksense config view` - view the qliksense operator CR
- `qliksense config delete-context` - deletes a specific context locally (not in-cluster). Deletes context in spec of `config.yaml` and locally deletes entire folder of specified context (does not delete secrets from cluster)
The global file which abstracts all contexts is `~/.qliksense/config.yaml`
```yaml
apiVersion: config.qlik.com/v1
kind: QliksenseConfig
metadata:
name: QliksenseConfigMetadata
spec:
contexts:
- name: qlik-default
crFile: /Users/xyz/.qliksense/contexts/qlik-default/qlik-default.yaml
- name: myqliksense
crFile: /Users/xyz/.qliksense/contexts/myqliksense/myqliksense.yaml
- name: hello
crFile: /Users/xyz/.qliksense/contexts/hello/hello.yaml
currentContext: hello
```

View File

@@ -1,96 +0,0 @@
# How CLI works
At the initialization, `qliksense` cli creates few files in the director `~/.qliksene` and it contains following files:
```console
.qliksense
├── config.yaml
├── contexts
│   └── qlik-default
│   └── qlik-default.yaml
└── ejson
└── keys
```
`qlik-default.yaml` is a default CR created with some default values like:
```yaml
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
spec:
profile: docker-desktop
secrets:
qliksense:
- name: mongodbUri
value: mongodb://qlik-default-mongodb:27017/qliksense?ssl=false
rotateKeys: "yes"
releaseName: qlik-default
```
The `qliksense` cli creates a default qliksense context (different from kubectl context) named `qlik-default` which will be the prefix for all kubernetes resources created by the cli under this context later on.
New context and configuration can be created by the cli, get available commands using:
```console
qliksense config -h
```
---
`qliksense` cli works in two modes
- With a git repo fork/clone of [qliksense-k8s](https://github.com/qlik-oss/qliksense-k8s)
- Without git repo
## Without git repo
In this mode `qliksense` CLI downloads the specified version from [qliksense-k8s](https://github.com/qlik-oss/qliksense-k8s) and places it in `~/.qliksense/contexts/<context-name>/qlik-k8s` folder.
The qliksense cli creates a CR for the QlikSense operator and all config operations are performed to edit the CR.
`qliksense install` or `qliksense config apply` will generate patches in local file system (i.e `~/.qliksense/contexts/<context-name>/qlik-k8s`) and
- Install those manifests into the cluster
- Create a custom resource (CR) for the `qliksene operator`.
The operator makes the association to the installed resources so that when `qliksense uninstall` is performed the operator can delete all kubernetes resources related to QSEoK for the current context.
## With a git repo
Create a fork or clone of [qliksense-k8s](https://github.com/qlik-oss/qliksense-k8s) and push it to your git repo/server
To add your repo into CR, perform the following:
```bash
qliksense config set git.repository="https://github.com/my-org/qliksense-k8s"
qliksense config set git.accessToken="<mySecretToken>"
```
When you perform `qliksense install` or `qliksene config apply`, qliksense operator performs these tasks:
- Download corresponding version of manifests from the your git repo
- Generate kustomize patches
- Install kubernetes resources
- Push generated patches into a new branch in the provided git repo. _Gives you ability to merge patches into your master branch_
- Create a CronJob to monitor master branch. Any changes pushed to master branch will be applied into the cluster. _This is a light weight `git-ops` model_
## GitOps
To enable gitops, the following section should be in the CR
```yaml
....
spec:
git:
repository: https://github.com/<OWNER>/<REPO>
accessToken: "<git-token>"
userName: "<git-username>"
gitOps:
enabled: "yes"
schedule: "*/5 * * * *"
watchBranch: <myBranch>
image: qlik-docker-oss.bintray.io/qliksense-repo-watcher
....
```

View File

@@ -1,53 +0,0 @@
# Getting started
## Requirements
- Kubernetes cluster (Docker Desktop with enabled Kubernetes)
- `kubectl` installed, configured and able to communicate with kubernetes cluster. _`qliksense` CLI uses `kubectl` under the hood to perform operations on cluster_
## Installing `qliksense` CLI
Download the executable for your platform from [releases page](https://github.com/qlik-oss/sense-installer/releases) and rename it to `qliksense`
??? tldr "Linux"
``` bash
curl -Lo qliksense https://github.com/qlik-oss/sense-installer/releases/download/v0.7.0/qliksense-linux-amd64
chmod +x qliksense
sudo mv qliksense /usr/local/bin
```
??? tldr "MacOS"
``` bash
curl -Lo qliksense https://github.com/qlik-oss/sense-installer/releases/download/v0.7.0/qliksense-darwin-amd64
chmod +x qliksense
sudo mv qliksense /usr/local/bin
```
??? tldr "Windows"
Download Windows executable and add it in your `PATH` as `qliksense.exe`
[https://github.com/qlik-oss/sense-installer/releases/download/v0.7.0/qliksense-windows-amd64.exe](https://github.com/qlik-oss/sense-installer/releases/download/v0.7.0/qliksense-windows-amd64.exe)
## Quick start
- To download the version `v0.0.2` from qliksense-k8s [releases](https://github.com/qlik-oss/qliksense-k8s/releases).
```shell
qliksense fetch v0.0.2
```
- To install CRDs for QSEoK and qliksense operator into the kubernetes cluster.
```shell
qliksense crds install --all
```
- To install QSEoK into a namespace in the kubernetes cluster where `kubectl` is pointing to.
```shell
qliksense install --acceptEULA="yes"
```

View File

@@ -1,15 +0,0 @@
# Overview
The Qlik Sense on Kubernetes CLI (`qliksense`) provides an imperative interface to many of the configurations that need to be applied against the declarative structure described in [qliksense-k8s](https://github.com/qlik-oss/qliksense-k8s).
The CLI facilitates:
- Installation of QSEoK
- Installation of qliksense operator to manage QSEoK
- Air gapped installation of QSEoK
!!! info ""
This is a technology preview that uses Qlik modified [kustomize](https://github.com/qlik-oss/kustomize) for Kubernetes manifests on [qliksense-k8s](https://github.com/qlik-oss/qliksense-k8s) repository
!!! info ""
See QlikSense [edge releases on qliksense-k8s](https://github.com/qlik-oss/qliksense-k8s/releases) repository

View File

@@ -1,33 +0,0 @@
# Postflight checks
Postflight checks are performed after qliksense is installed on the cluster and during normal operating mode of the product. Such checks can range from validating certain conditions to checking the status of certain operations or entities on the kubernetes cluster.
Run the following command to view help about the commands supported by postflight at any moment:
```
$ qliksense postflight
perform postflight checks on the cluster
Usage:
qliksense postflight [command]
Examples:
qliksense postflight <postflight_check_to_run>
Available Commands:
db-migration-check check mongodb migration status on the cluster
Flags:
-h, --help help for postflight
-v, --verbose verbose mode
```
### DB migration check
This command checks init containers for successful database migrarion completions, and reports failure, if any to the user.
An example run of this check produces an output as shown below:
```shell
$ qliksense postflight db-migration-check
Logs from pod: qliksense-users-6977cb7788-cxxwh
{"caller":"main.go:39","environment":"qseok","error":"error parsing uri: scheme must be \"mongodb\" or \"mongodb+srv\"","level":"error","message":"failed to connect to ","timestamp":"2020-06-01T01:07:18.4170507Z","version":""}
Postflight db_migration_check completed
```

View File

@@ -1,307 +0,0 @@
# Preflight checks
Preflight checks provide pre-installation cluster conformance testing and validation before we install qliksense on the cluster. We gather a suite of conformance tests that can be easily written and run on the target cluster to verify that cluster-specific requirements are met.
We support a couple of tests at the moment as part of preflight checks, and the range of the suite will be expanded in future.
Run the following command to view help about the commands supported by preflight at any moment:
```shell
$ qliksense preflight
perform preflight checks on the cluster
Usage:
qliksense preflight [command]
Examples:
qliksense preflight <preflight_check_to_run>
Available Commands:
all perform all checks
authcheck preflight authcheck
clean perform preflight clean
deployment perform preflight deployment check
dns perform preflight dns check
k8s-version check kubernetes version
mongo preflight mongo OR preflight mongo --url=<url>
pod perform preflight pod check
role preflight create role check
rolebinding preflight create rolebinding check
service perform preflight service check
serviceaccount preflight create ServiceAccount check
Flags:
-h, --help help for preflight
-v, --verbose verbose mode
```
### DNS check
Run the following command to perform preflight DNS check. We setup a kubernetes deployment and try to reach it as part of establishing DNS connectivity in this check.
The expected output should be similar to the one shown below.
```shell
$ qliksense preflight dns -v
Preflight DNS check
---------------------
Created deployment "dep-dns-preflight-check"
Created service "svc-dns-pf-check"
Created pod: pf-pod-1
Fetching pod: pf-pod-1
Fetching pod: pf-pod-1
Exec-ing into the container...
Preflight DNS check: PASSED
Completed preflight DNS check
Cleaning up resources...
Deleted pod: pf-pod-1
Deleted service: svc-dns-pf-check
Deleted deployment: dep-dns-preflight-check
```
### Kubernetes version check
We check the version of the target kubernetes cluster and ensure that it falls in the valid range of kubernetes versions that are supported by qliksense.
The command to run this check and the expected similar output are as shown below:
```shell
$ qliksense preflight k8s-version -v
Preflight kubernetes minimum version check
------------------------------------------
Kubernetes API Server version: v1.15.5
Current K8s Version: 1.15.5
Current 1.15.5 is greater than minimum required version:1.11.0, hence good to go
Preflight minimum kubernetes version check: PASSED
Completed Preflight kubernetes minimum version check
```
### Service check
We use the commmand below to test if we are able to create a service in the cluster.
```shell
$ qliksense preflight service -v
Preflight service check
-----------------------
Preflight service check:
Created service "svc-pf-check"
Preflight service creation check: PASSED
Cleaning up resources...
Deleted service: svc-pf-check
Completed preflight service check
```
### Deployment check
We use the commmand below to test if we are able to create a deployment in the cluster. After the test exexutes, we wait until the created deployment terminates before we exit the command.
```shell
$ qliksense preflight deployment -v
Preflight deployment check
-----------------------
Preflight deployment check:
Created deployment "deployment-preflight-check"
Preflight Deployment check: PASSED
Cleaning up resources...
Deleted deployment: deployment-preflight-check
Completed preflight deployment check
```
### Pod check
We use the commmand below to test if we are able to create a pod in the cluster.
```shell
$ qliksense preflight pod -v
Preflight pod check
--------------------
Preflight pod check:
Created pod: pod-pf-check
Preflight pod creation check: PASSED
Cleaning up resources...
Deleted pod: pod-pf-check
Completed preflight pod check
```
### Role check
We use the command below to test if we are able to create a role in the cluster
```shell
$ qliksense preflight role -v
Preflight role check
---------------------------
Preflight role check:
Created role: role-preflight-check
Preflight role check: PASSED
Cleaning up resources...
Deleted role: role-preflight-check
Completed preflight role check
```
### RoleBinding check
We use the command below to test if we are able to create a role binding in the cluster
```shell
$ qliksense preflight rolebinding -v
Preflight rolebinding check
---------------------------
Preflight rolebinding check:
Created RoleBinding: role-binding-preflight-check
Preflight rolebinding check: PASSED
Cleaning up resources...
Deleting RoleBinding: role-binding-preflight-check
Deleted RoleBinding: role-binding-preflight-check
Completed preflight rolebinding check
```
### Create-ServiceAccount check
We use the command below to test if we are able to create a service account in the cluster
```shell
$ qliksense preflight serviceaccount -v
Preflight ServiceAccount check
-------------------------------------
Preflight serviceaccount check:
Created Service Account: preflight-check-test-serviceaccount
Preflight serviceaccount check: PASSED
Cleaning up resources...
Deleting ServiceAccount: preflight-check-test-serviceaccount
Deleted ServiceAccount: preflight-check-test-serviceaccount
Completed preflight serviceaccount check
```
### Auth check
We use the command below to combine creation of role, role binding, and service account tests
```shell
$ qliksense preflight authcheck -v
Preflight auth check
-------------------------------------
Preflight create-role check:
Created role: role-preflight-check
Preflight create-role check: PASSED
Cleaning up resources...
Deleted role: role-preflight-check
Completed preflight create-role check
Preflight create RoleBinding check:
Created RoleBinding: role-binding-preflight-check
Preflight create RoleBinding check: PASSED
Cleaning up resources...
Deleted RoleBinding: role-binding-preflight-check
Completed preflight create RoleBinding check
Preflight createServiceAccount check:
Created Service Account: preflight-check-test-serviceaccount
Preflight createServiceAccount check: PASSED
Cleaning up resources...
Deleted ServiceAccount: preflight-check-test-serviceaccount
Completed preflight createServiceAccount check
Completed preflight auth check
```
### Mongodb check
We can check if we are able to connect to an instance of mongodb on the cluster by either supplying the mongodbUri as part of the command or infer it from the current context.
```shell
qliksense preflight mongo --url=<url> -v OR
qliksense preflight mongo -v
qliksense preflight mongo --url=<mongo-server url> --ca-cert=<path to ca-cert file> -v
```
```shell
Preflight mongo check
---------------------
Preflight mongodb check:
Created pod: pf-mongo-pod
stdout: MongoDB shell version v4.2.5
connecting to: <url>/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("...") }
MongoDB server version: 4.2.5
bye
stderr:
Preflight mongo check: PASSED
Deleted pod: pf-mongo-pod
Completed preflight mongodb check
```
#### Mongodb check with mutual tls
In order to perform mutual tls with mongo we need to:
- append client certificate to the beginning/end of CA certificate. Make sure to include the beginning and end tags on each certificate.
The CA certificate file should look like this in the end:
```shell
<existing contents of CA cert>
...
-----BEGIN RSA PRIVATE KEY-----
<private key>
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
<public key>
-----END CERTIFICATE-----
```
- Run the command below to set the ca certificate into the CR
```shell
cat <path_to_ca.crt> | base64 | qliksense config set-secrets qliksense.caCertificates --base64
```
Next, run:
```shell
qliksense preflight mongo -v
```
### Running all checks
Run the command shown below to execute all preflight checks.
```shell
$ qliksense preflight all --mongodb-url=<url> -v OR
$ qliksense preflight all --mongodb-url=<mongo-server url> --mongodb-ca-cert=<path to ca-cert file> -v
Running all preflight checks
Preflight DNS check
-------------------
Created deployment "dep-dns-preflight-check"
Created service "svc-dns-pf-check"
Created pod: pf-pod-1
Fetching pod: pf-pod-1
Fetching pod: pf-pod-1
Exec-ing into the container...
Preflight DNS check: PASSED
Completed preflight DNS check
Cleaning up resources...
Deleted pod: pf-pod-1
Deleted service: svc-dns-pf-check
Deleted deployment: dep-dns-preflight-check
Preflight kubernetes minimum version check
------------------------------------------
Kubernetes API Server version: v1.15.5
Current K8s Version: 1.15.5
Current 1.15.5 is greater than minimum required version:1.11.0, hence good to go
Preflight minimum kubernetes version check: PASSED
Completed Preflight kubernetes minimum version check
...
...
All preflight checks have PASSED
Completed running all preflight checks
```
### Clean
Run the command below to cleanup entities that were created for the purpose of running preflight checks and left behind in the cluster.
```shell
$ qliksense preflight clean -v
Preflight clean
----------------
Removing deployment...
Removing service...
Removing pod...
Removing role...
Removing rolebinding...
Removing serviceaccount...
Removing DNS check components...
Removing mongo check components...
Preflight cleanup complete
```

104
go.mod
View File

@@ -3,60 +3,74 @@ module github.com/qlik-oss/sense-installer
go 1.13
replace (
github.com/Sirupsen/logrus v1.0.5 => github.com/sirupsen/logrus v1.0.5
github.com/Sirupsen/logrus v1.3.0 => github.com/Sirupsen/logrus v1.0.6
github.com/Sirupsen/logrus v1.4.0 => github.com/sirupsen/logrus v1.0.6
// github.com/containerd/containerd v1.3.0-0.20190507210959-7c1e88399ec0 => github.com/containerd/containerd v1.3.2
github.com/docker/docker => github.com/moby/moby v0.7.3-0.20190826074503-38ab9da00309
// github.com/jaguilar/vt100 => github.com/tonistiigi/vt100 v0.0.0-20190402012908-ad4c4a574305
// golang.org/x/crypto v0.0.0-20190129210102-0709b304e793 => golang.org/x/crypto v0.0.0-20180904163835-0709b304e793
golang.org/x/sys => golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a
k8s.io/apimachinery => k8s.io/apimachinery v0.17.0
k8s.io/client-go => k8s.io/client-go v0.17.0
k8s.io/kubectl => k8s.io/kubectl v0.0.0-20191219154910-1528d4eea6dd
sigs.k8s.io/kustomize/api => github.com/qlik-oss/kustomize/api v0.3.3-0.20200604075616-c46582ece468
)
require (
cloud.google.com/go v0.52.0 // indirect
cloud.google.com/go/storage v1.5.0 // indirect
github.com/Masterminds/semver/v3 v3.1.0
github.com/Shopify/ejson v1.2.1
github.com/aws/aws-sdk-go v1.28.9 // indirect
get.porter.sh/porter v0.22.0-beta.1
github.com/Masterminds/semver v1.5.0 // indirect
github.com/Microsoft/hcsshim v0.8.7 // indirect
github.com/PaesslerAG/jsonpath v0.1.1 // indirect
github.com/PuerkitoBio/goquery v1.5.0 // indirect
github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d // indirect
github.com/agl/ed25519 v0.0.0-20170116200512-5312a6153412 // indirect
github.com/bitly/go-hostpool v0.0.0-20171023180738-a3a6125de932 // indirect
github.com/bitly/go-simplejson v0.5.0 // indirect
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect
github.com/bugsnag/bugsnag-go v1.5.3 // indirect
github.com/containers/image/v5 v5.1.0
github.com/bugsnag/panicwrap v1.2.0 // indirect
github.com/carolynvs/datetime-printer v0.2.0 // indirect
github.com/cbroglie/mustache v1.0.1 // indirect
github.com/cenkalti/backoff v2.2.1+incompatible // indirect
github.com/cloudflare/cfssl v1.4.1 // indirect
github.com/containerd/containerd v1.3.2 // indirect
github.com/containerd/continuity v0.0.0-20191214063359-1097c8bae83b // indirect
github.com/deislabs/cnab-go v0.7.1-beta1 // indirect
github.com/docker/cli v0.0.0-20191212191748-ebca1413117a
github.com/docker/cnab-to-oci v0.3.0-beta2 // indirect
github.com/docker/distribution v2.7.1+incompatible
github.com/docker/docker v1.4.2-0.20190924003213-a8608b5b67c7
github.com/docker/go v1.5.1-1 // indirect
github.com/docker/go-metrics v0.0.1 // indirect
github.com/go-git/go-git/v5 v5.0.0
github.com/gobuffalo/envy v1.9.0 // indirect
github.com/gobuffalo/logger v1.0.3 // indirect
github.com/gobuffalo/packd v1.0.0 // indirect
github.com/gobuffalo/packr/v2 v2.7.1
github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 // indirect
github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8 // indirect
github.com/gobuffalo/packr/v2 v2.7.1 // indirect
github.com/gofrs/uuid v3.2.0+incompatible // indirect
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect
github.com/golang/protobuf v1.3.3 // indirect
github.com/gorilla/mux v1.7.3 // indirect
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a
github.com/google/go-containerregistry v0.0.0-20191216221554-74b082017bc4 // indirect
github.com/gophercloud/gophercloud v0.7.0 // indirect
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed // indirect
github.com/hashicorp/go-hclog v0.10.0 // indirect
github.com/hashicorp/go-plugin v1.0.1 // indirect
github.com/imdario/mergo v0.3.8 // indirect
github.com/jinzhu/gorm v1.9.11 // indirect
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 // indirect
github.com/logrusorgru/aurora v0.0.0-20200102142835-e9ef32dff381
github.com/mattn/go-colorable v0.1.4
github.com/mattn/go-tty v0.0.3
github.com/lib/pq v1.2.0 // indirect
github.com/mattn/go-sqlite3 v2.0.1+incompatible // indirect
github.com/miekg/pkcs11 v1.0.3 // indirect
github.com/mitchellh/go-homedir v1.1.0
github.com/otiai10/copy v1.1.1
github.com/pkg/errors v0.9.1
github.com/qlik-oss/k-apis v0.1.5
github.com/robfig/cron/v3 v3.0.1
github.com/rogpeppe/go-internal v1.5.2 // indirect
github.com/spf13/cobra v0.0.6
github.com/mmcdole/gofeed v1.0.0-beta2 // indirect
github.com/mmcdole/goxpp v0.0.0-20181012175147-0068e33feabf // indirect
github.com/olekukonko/tablewriter v0.0.4 // indirect
github.com/opencontainers/runc v0.1.1 // indirect
github.com/pivotal/image-relocation v0.0.0-20191111101224-e94aff6df06c // indirect
github.com/qri-io/jsonschema v0.1.1 // indirect
github.com/spf13/cobra v0.0.5
github.com/spf13/viper v1.6.1
golang.org/x/crypto v0.0.0-20200311171314-f7b00557c8c4 // indirect
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a // indirect
golang.org/x/net v0.0.0-20200528225125-3c3fba18258b
golang.org/x/tools v0.0.0-20200312194400-c312e98713c2 // indirect
google.golang.org/genproto v0.0.0-20200128133413-58ce757ed39b // indirect
gopkg.in/yaml.v2 v2.2.8
k8s.io/api v0.17.2
k8s.io/apiextensions-apiserver v0.17.2
k8s.io/apimachinery v0.17.2
k8s.io/client-go v11.0.0+incompatible
sigs.k8s.io/kustomize/api v0.3.2
sigs.k8s.io/yaml v1.1.0
github.com/theupdateframework/notary v0.6.1 // indirect
github.com/xlab/handysort v0.0.0-20150421192137-fb3537ed64a1 // indirect
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553
gopkg.in/AlecAivazis/survey.v1 v1.8.7 // indirect
gopkg.in/dancannon/gorethink.v3 v3.0.5 // indirect
gopkg.in/fatih/pool.v2 v2.0.0 // indirect
gopkg.in/gorethink/gorethink.v3 v3.0.5 // indirect
gopkg.in/yaml.v2 v2.2.7
vbom.ml/util v0.0.0-20180919145318-efcd4e0f9787 // indirect
)
exclude github.com/Azure/go-autorest v12.0.0+incompatible

1143
go.sum

File diff suppressed because it is too large Load Diff

View File

@@ -1,23 +0,0 @@
site_name: Qlik Sense on Kubernetes CLI
repo_url: 'https://github.com/qlik-oss/sense-installer'
strict: true
theme:
name: "material"
palette:
primary: 'green'
accent: 'indigo'
markdown_extensions:
- toc:
permalink: true
- admonition
- codehilite
- pymdownx.inlinehilite
- pymdownx.superfences
- pymdownx.details
nav:
- Overview: index.md
- getting_started.md
- command_reference.md
- concepts.md
- air_gap.md
- Releases ⧉: https://github.com/qlik-oss/sense-installer/releases

BIN
pkg/.DS_Store vendored

Binary file not shown.

View File

@@ -1,574 +0,0 @@
package api
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/qlik-oss/k-apis/pkg/config"
b64 "encoding/base64"
"github.com/jinzhu/copier"
)
const (
pushSecretFileName = "image-registry-push-secret.yaml"
pullSecretFileName = "image-registry-pull-secret.yaml"
qliksenseContextsDirName = "contexts"
qliksenseSecretsDirName = "secrets"
qliksenseEjsonDirName = "ejson"
QLIK_GIT_REPO = "https://github.com/qlik-oss/qliksense-k8s"
)
// NewQConfig create QliksenseConfig object from file ~/.qliksense/config.yaml
func NewQConfig(qsHome string) *QliksenseConfig {
qc, err := NewQConfigE(qsHome)
if err != nil {
fmt.Println("yaml unmarshalling error ", err)
os.Exit(1)
}
return qc
}
func NewQConfigE(qsHome string) (*QliksenseConfig, error) {
configFile := filepath.Join(qsHome, "config.yaml")
qc := &QliksenseConfig{}
err := ReadFromFile(qc, configFile)
if err != nil {
return nil, err
}
qc.QliksenseHomePath = qsHome
return qc, nil
}
func NewQConfigEmpty(qsHome string) *QliksenseConfig {
return &QliksenseConfig{
QliksenseHomePath: qsHome,
}
}
// GetCR create a QliksenseCR object for a particular context
// from file ~/.qliksense/contexts/<contx-name>/<contx-name>.yaml
func (qc *QliksenseConfig) GetCR(contextName string) (*QliksenseCR, error) {
crFilePath := qc.GetCRFilePath(contextName)
if crFilePath == "" {
return nil, errors.New("context name " + contextName + " not found")
}
return qc.GetAndTransformCrObject(crFilePath)
}
// GetCurrentCR create a QliksenseCR object for current context
func (qc *QliksenseConfig) GetCurrentCR() (*QliksenseCR, error) {
return qc.GetCR(qc.Spec.CurrentContext)
}
// SetCrLocation sets the CR location for a context. Helpful during test
func (qc *QliksenseConfig) SetCrLocation(contextName, filePath string) (*QliksenseConfig, error) {
tempQc := &QliksenseConfig{}
copier.Copy(tempQc, qc)
found := false
tempQc.Spec.Contexts = []Context{}
for _, c := range qc.Spec.Contexts {
if c.Name == contextName {
c.CrFile = filePath
found = true
}
tempQc.Spec.Contexts = append(tempQc.Spec.Contexts, []Context{c}...)
}
if found {
return tempQc, nil
}
return nil, errors.New("cannot find the context")
}
// GetCRObject create a qliksense CR object from file
func GetCRObject(crfile string) (*QliksenseCR, error) {
cr := &QliksenseCR{}
err := ReadFromFile(cr, crfile)
if err != nil {
fmt.Println("cannot unmarshal cr ", err)
return nil, err
}
return cr, nil
}
func (qc *QliksenseConfig) GetAndTransformCrObject(crfile string) (*QliksenseCR, error) {
cr, err := GetCRObject(crfile)
if err != nil {
return nil, err
}
if cr.Spec.ManifestsRoot != "" && !filepath.IsAbs(cr.Spec.ManifestsRoot) {
cr.Spec.ManifestsRoot = filepath.Join(qc.QliksenseHomePath, cr.Spec.ManifestsRoot)
}
return cr, nil
}
//CreateCRObjectFromString create a QliksenseCR from string content
func CreateCRObjectFromString(crContent string) (*QliksenseCR, error) {
if crContent == "" {
return nil, errors.New("empty string cannot qliksensecr")
}
cr := &QliksenseCR{}
err := ReadFromStream(cr, strings.NewReader(crContent))
if err != nil {
fmt.Println("cannot unmarshal cr ", err)
return nil, err
}
return cr, nil
}
func (qc *QliksenseConfig) GetCRFilePath(contextName string) string {
crFilePath := ""
for _, ctx := range qc.Spec.Contexts {
if ctx.Name == contextName {
crFilePath = filepath.Join(qc.QliksenseHomePath, ctx.CrFile)
break
}
}
return crFilePath
}
func (cr *QliksenseCR) IsRepoExist() bool {
if cr.Spec.ManifestsRoot == "" {
return false
}
if _, err := os.Lstat(cr.Spec.ManifestsRoot); err != nil {
return false
}
return true
}
func (cr *QliksenseCR) GetFetchUrl() string {
if cr.Spec.FetchSource == nil || cr.Spec.FetchSource.Repository == "" {
return QLIK_GIT_REPO
}
return cr.Spec.FetchSource.Repository
}
func (cr *QliksenseCR) GetFetchAccessToken(encryptionKey string) string {
if cr.Spec.FetchSource == nil {
return ""
}
if tok, err := cr.Spec.FetchSource.GetAccessToken(); err != nil {
fmt.Println(err)
return ""
} else if tok == "" {
return tok
} else {
by, _ := b64.StdEncoding.DecodeString(tok)
res, err := DecryptData(by, encryptionKey)
if err != nil {
fmt.Println(err)
return ""
}
return string(res)
}
}
func (cr *QliksenseCR) SetFetchUrl(url string) {
if cr.Spec.FetchSource == nil {
cr.Spec.FetchSource = &config.Repo{}
}
cr.Spec.FetchSource.Repository = url
}
func (cr *QliksenseCR) SetFetchAccessToken(token, encryptionKey string) error {
if cr.Spec.FetchSource == nil {
cr.Spec.FetchSource = &config.Repo{}
}
res, err := EncryptData([]byte(token), encryptionKey)
if err != nil {
return err
}
cr.Spec.FetchSource.AccessToken = b64.StdEncoding.EncodeToString(res)
return nil
}
func (cr *QliksenseCR) SetFetchAccessSecretName(sec string) {
if cr.Spec.FetchSource == nil {
cr.Spec.FetchSource = &config.Repo{}
}
cr.Spec.FetchSource.SecretName = sec
}
//DeleteRepo delete the manifest repo and unset manifestsRoot
func (cr *QliksenseCR) DeleteRepo() error {
if err := os.RemoveAll(cr.Spec.ManifestsRoot); err != nil {
return err
}
cr.Spec.ManifestsRoot = ""
return nil
}
func (qc *QliksenseConfig) IsRepoExist(contextName, version string) bool {
if _, err := os.Lstat(qc.BuildRepoPathForContext(contextName, version)); err != nil {
return false
}
return true
}
func (qc *QliksenseConfig) IsRepoExistForCurrent(version string) bool {
if _, err := os.Lstat(qc.BuildRepoPath(version)); err != nil {
return false
}
return true
}
func (qc *QliksenseConfig) DeleteRepoForCurrent(version string) error {
path := qc.BuildRepoPath(version)
return os.RemoveAll(path)
}
func (qc *QliksenseConfig) BuildRepoPath(version string) string {
return qc.BuildRepoPathForContext(qc.Spec.CurrentContext, version)
}
func (qc *QliksenseConfig) BuildRepoPathForContext(contextName, version string) string {
return filepath.Join(qc.GetContextPath(contextName), "qlik-k8s", version)
}
func (qc *QliksenseConfig) BuildCurrentManifestsRoot(version string) string {
return qc.BuildRepoPath(version)
}
func (qc *QliksenseConfig) WriteCR(cr *QliksenseCR) error {
crf := qc.GetCRFilePath(cr.GetName())
if crf == "" {
return errors.New("context name " + cr.GetName() + " not found")
}
return qc.TransformAndWriteCr(cr, crf)
}
//CreateOrWriteCrAndContext create necessary folder structure, update config.yaml and context yaml files
func (qc *QliksenseConfig) CreateOrWriteCrAndContext(cr *QliksenseCR) error {
if qc.QliksenseHomePath == "" {
return errors.New("qliksense home is not set")
}
crf := qc.GetCRFilePath(cr.GetName())
if crf == "" {
// create direcotry structure for context
cDir := filepath.Join(qc.QliksenseHomePath, "contexts", cr.GetName())
if err := os.MkdirAll(cDir, os.ModePerm); err != nil {
return err
}
crf = filepath.Join(cDir, cr.GetName()+".yaml")
ctx := Context{
Name: cr.GetName(),
CrFile: "contexts/" + cr.GetName() + "/" + cr.GetName() + ".yaml", //filepath.Join("contexts", cr.GetName(), cr.GetName()+".yaml"),
}
qc.AddToContexts(ctx)
if err := qc.Write(); err != nil {
return err
}
}
return qc.TransformAndWriteCr(cr, crf)
}
func (qc *QliksenseConfig) TransformAndWriteCr(cr *QliksenseCR, file string) error {
if strings.HasPrefix(cr.Spec.ManifestsRoot, qc.QliksenseHomePath) {
cr.Spec.ManifestsRoot = strings.Replace(cr.Spec.ManifestsRoot, qc.QliksenseHomePath+"/", "", 1)
cr.Spec.ManifestsRoot = strings.Replace(cr.Spec.ManifestsRoot, qc.QliksenseHomePath+"\\", "", 1)
cr.Spec.ManifestsRoot = strings.Replace(cr.Spec.ManifestsRoot, "\\", "/", -1)
}
if err := WriteToFile(cr, file); err != nil {
return err
}
if cr.Spec.ManifestsRoot != "" {
cr.Spec.ManifestsRoot = filepath.Join(qc.QliksenseHomePath, cr.Spec.ManifestsRoot)
}
return nil
}
func (qc *QliksenseConfig) AddToContexts(ctx Context) error {
//TODO: additional duplicate check may be added latter
qc.Spec.Contexts = append(qc.Spec.Contexts, ctx)
return nil
}
func (qc *QliksenseConfig) WriteCurrentContextCR(cr *QliksenseCR) error {
return qc.WriteCR(cr)
}
func (qc *QliksenseConfig) IsContextExist(ctxName string) bool {
for _, ct := range qc.Spec.Contexts {
if ct.Name == ctxName {
return true
}
}
return false
}
func (qc *QliksenseConfig) GetCurrentContextDir() (string, error) {
if qcr, err := qc.GetCurrentCR(); err != nil {
return "", err
} else {
return filepath.Join(qc.QliksenseHomePath, qliksenseContextsDirName, qcr.GetObjectMeta().GetName()), nil
}
}
func (qc *QliksenseConfig) GetCurrentContextSecretsDir() (string, error) {
if currentContextDir, err := qc.GetCurrentContextDir(); err != nil {
return "", err
} else {
return filepath.Join(currentContextDir, qliksenseSecretsDirName), nil
}
}
func (qc *QliksenseConfig) setDockerConfigJsonSecret(filename string, dockerConfigJsonSecret *DockerConfigJsonSecret) error {
if secretsDir, err := qc.GetCurrentContextSecretsDir(); err != nil {
return err
} else if encryptionKey, err := qc.GetEncryptionKeyForCurrent(); err != nil {
return err
} else if dockerConfigJsonSecretYaml, err := dockerConfigJsonSecret.ToYaml(encryptionKey); err != nil {
return err
} else if err := os.MkdirAll(secretsDir, os.ModePerm); err != nil {
return err
} else {
return ioutil.WriteFile(filepath.Join(secretsDir, filename), dockerConfigJsonSecretYaml, os.ModePerm)
}
}
func (qc *QliksenseConfig) SetPushDockerConfigJsonSecret(dockerConfigJsonSecret *DockerConfigJsonSecret) error {
return qc.setDockerConfigJsonSecret(pushSecretFileName, dockerConfigJsonSecret)
}
func (qc *QliksenseConfig) SetPullDockerConfigJsonSecret(dockerConfigJsonSecret *DockerConfigJsonSecret) error {
return qc.setDockerConfigJsonSecret(pullSecretFileName, dockerConfigJsonSecret)
}
func (qc *QliksenseConfig) GetPushDockerConfigJsonSecret() (*DockerConfigJsonSecret, error) {
return qc.getDockerConfigJsonSecret(pushSecretFileName)
}
func (qc *QliksenseConfig) GetPullDockerConfigJsonSecret() (*DockerConfigJsonSecret, error) {
return qc.getDockerConfigJsonSecret(pullSecretFileName)
}
func (qc *QliksenseConfig) DeletePushDockerConfigJsonSecret() error {
return qc.deleteDockerConfigJsonSecret(pushSecretFileName)
}
func (qc *QliksenseConfig) DeletePullDockerConfigJsonSecret() error {
return qc.deleteDockerConfigJsonSecret(pullSecretFileName)
}
func (qc *QliksenseConfig) deleteDockerConfigJsonSecret(name string) error {
if secretsDir, err := qc.GetCurrentContextSecretsDir(); err != nil {
return err
} else {
return os.Remove(filepath.Join(secretsDir, name))
}
}
func (qc *QliksenseConfig) getDockerConfigJsonSecret(name string) (*DockerConfigJsonSecret, error) {
dockerConfigJsonSecret := &DockerConfigJsonSecret{}
if secretsDir, err := qc.GetCurrentContextSecretsDir(); err != nil {
return nil, err
} else if dockerConfigJsonSecretYaml, err := ioutil.ReadFile(filepath.Join(secretsDir, name)); err != nil {
return nil, err
} else if encryptionKey, err := qc.GetEncryptionKeyForCurrent(); err != nil {
return nil, err
} else if err := dockerConfigJsonSecret.FromYaml(dockerConfigJsonSecretYaml, encryptionKey); err != nil {
return nil, err
}
return dockerConfigJsonSecret, nil
}
func (qc *QliksenseConfig) getCurrentContextEncryptionKeyPairLocation() (string, error) {
if qcr, err := qc.GetCurrentCR(); err != nil {
return "", err
} else {
return qc.getContextEncryptionKeyLocation(qcr.GetName())
}
}
func (qc *QliksenseConfig) getContextEncryptionKeyLocation(contextName string) (string, error) {
// Check env var: QLIKSENSE_KEY_LOCATION to determine location to store keypair
var secretKeyPairLocation string
if os.Getenv("QLIKSENSE_KEY_LOCATION") != "" {
LogDebugMessage("Env variable: QLIKSENSE_KEY_LOCATION= %s", os.Getenv("QLIKSENSE_KEY_LOCATION"))
secretKeyPairLocation = os.Getenv("QLIKSENSE_KEY_LOCATION")
} else {
// QLIKSENSE_KEY_LOCATION has not been set, hence storing key pair in default location:
// /.qliksense/secrets/contexts/<current-context>/secrets/
secretKeyPairLocation = filepath.Join(qc.QliksenseHomePath, qliksenseSecretsDirName, qliksenseContextsDirName, contextName, qliksenseSecretsDirName)
}
return secretKeyPairLocation, os.MkdirAll(secretKeyPairLocation, os.ModePerm)
}
func (qc *QliksenseConfig) GetCurrentContextEjsonKeyDir() (string, error) {
if qcr, err := qc.GetCurrentCR(); err != nil {
return "", err
} else {
ejsonKeyDir := filepath.Join(qc.QliksenseHomePath, qliksenseSecretsDirName, qliksenseContextsDirName, qcr.GetObjectMeta().GetName(), qliksenseEjsonDirName)
if err := os.MkdirAll(ejsonKeyDir, os.ModePerm); err != nil {
return "", err
}
return ejsonKeyDir, nil
}
}
func (qc *QliksenseConfig) GetEncryptionKeyForCurrent() (string, error) {
if qcr, err := qc.GetCurrentCR(); err != nil {
return "", err
} else {
return qc.GetEncryptionKeyFor(qcr.GetName())
}
}
func (qc *QliksenseConfig) GetEncryptionKeyFor(contextName string) (string, error) {
secretKeyLocation, err := qc.getContextEncryptionKeyLocation(contextName)
if err != nil {
return "", err
}
key, err := LoadSecretKey(secretKeyLocation)
if key != "" {
return key, nil
}
fmt.Println("Generating new encryption key for the context: " + contextName)
return GenerateAndStoreSecretKey(secretKeyLocation)
}
func (cr *QliksenseCR) AddLabelToCr(key, value string) {
m := cr.GetObjectMeta().GetLabels()
if m == nil {
m = make(map[string]string)
}
m[key] = value
cr.GetObjectMeta().SetLabels(m)
}
func (cr *QliksenseCR) GetLabelFromCr(key string) string {
return cr.GetObjectMeta().GetLabels()[key]
}
func (cr *QliksenseCR) GetString() (string, error) {
out, err := K8sToYaml(cr)
if err != nil {
fmt.Println("cannot unmarshal cr ", err)
return "", err
}
return string(out), nil
}
func (cr *QliksenseCR) GetK8sSecretsFolder(qlikSenseHomeDir string) string {
return filepath.Join(qlikSenseHomeDir, qliksenseContextsDirName, cr.GetName(), qliksenseSecretsDirName)
}
func (cr *QliksenseCR) IsEULA() bool {
for k, nvs := range cr.Spec.Configs {
if k == "qliksense" {
for _, nv := range nvs {
if nv.Name == "acceptEULA" {
return nv.Value == "yes"
}
}
}
}
return false
}
func (cr *QliksenseCR) SetEULA(value string) {
cr.Spec.AddToConfigs("qliksense", "acceptEULA", value)
}
// GetCustomCrdsPath get crds path if exist in the profile dir
func (cr *QliksenseCR) GetCustomCrdsPath() string {
if cr.Spec.ManifestsRoot == "" || cr.Spec.Profile == "" {
return ""
}
crdsPath := filepath.Join(cr.Spec.GetManifestsRoot(), "manifests", cr.Spec.Profile, "crds")
if _, err := os.Lstat(crdsPath); err != nil {
return ""
}
return crdsPath
}
// GetDecryptedCr it decrypts all the encrypted value and return a new CR
func (qc *QliksenseConfig) GetDecryptedCr(cr *QliksenseCR) (*QliksenseCR, error) {
newCr := &QliksenseCR{}
copier.Copy(newCr, cr)
encryptionKey, err := qc.GetEncryptionKeyFor(cr.GetName())
if err != nil {
return nil, err
}
finalSecrets := map[string]config.NameValues{}
for k, nvs := range newCr.Spec.Secrets {
newNvs := config.NameValues{}
for _, nv := range nvs {
if nv.Value != "" {
b, err := b64.StdEncoding.DecodeString(strings.TrimSpace(nv.Value))
if err != nil {
return nil, err
}
db, err := DecryptData(b, encryptionKey)
if err != nil {
return nil, err
}
newNvs = append(newNvs, config.NameValue{
Name: nv.Name,
Value: string(db),
})
}
}
finalSecrets[k] = newNvs
}
newCr.Spec.Secrets = finalSecrets
if newCr.Spec.FetchSource != nil && newCr.Spec.FetchSource.AccessToken != "" {
decData := cr.GetFetchAccessToken(encryptionKey)
newCr.Spec.FetchSource.AccessToken = decData
}
return newCr, nil
}
//Validate validate CR
func (cr *QliksenseCR) Validate() bool {
return true
}
//CreateContextDirs create context dir structure ~/.qliksense/contexts/contextName
func (qc *QliksenseConfig) CreateContextDirs(contextName string) error {
return os.MkdirAll(qc.GetContextPath(contextName), os.ModePerm)
}
func (qc *QliksenseConfig) GetContextPath(contextName string) string {
return filepath.Join(qc.QliksenseHomePath, qliksenseContextsDirName, contextName)
}
//BuildCrFileAbsolutePath build absolute path for a cr ie. ~/.qliksense/contexts/qlik-defautl/qlik-default.yaml
func (qc *QliksenseConfig) BuildCrFileAbsolutePath(contextName string) string {
return filepath.Join(qc.GetContextPath(contextName), contextName+".yaml")
}
//BuildCrFilePath build cr file path i.e. contexts/qlik-default/qlik-default.yaml
func (qc *QliksenseConfig) BuildCrFilePath(contextName string) string {
return filepath.Join(qc.GetContextPath(contextName), contextName+".yaml")
}
//AddToContexts add the context into qc.Spec.Contexts
func (qc *QliksenseConfig) AddToContextsRaw(crName, crFile string) {
qc.Spec.Contexts = append(qc.Spec.Contexts, []Context{
{CrFile: crFile,
Name: crName},
}...)
}
//SetCurrentContextName set the qc.Spec.CurrentContext
func (qc *QliksenseConfig) SetCurrentContextName(name string) {
qc.Spec.CurrentContext = name
}
//Write write QliksenseConfig into config.yaml
func (qc *QliksenseConfig) Write() error {
return WriteToFile(qc, filepath.Join(qc.QliksenseHomePath, "config.yaml"))
}

View File

@@ -1,172 +0,0 @@
package api
import (
b64 "encoding/base64"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"testing"
)
const tempPermissionCode os.FileMode = 0777
func setup() (func(), string) {
dir, _ := ioutil.TempDir("", "testing_path")
config :=
`
apiVersion: config.qlik.com/v1
kind: QliksenseConfig
metadata:
name: whatever
spec:
contexts:
- name: contx1
crLocation: /Users/mqb/.qliksense/contexts/contx1
- name: cotx2
crLocation: /root/.qliksense/contexts/cotx2.yaml
currentContext: contx1
`
configFile := filepath.Join(dir, "config.yaml")
ioutil.WriteFile(configFile, []byte(config), tempPermissionCode)
tearDown := func() {
os.RemoveAll(dir)
}
return tearDown, dir
}
func createCRFile(homeDir string) {
cr :=
`
apiVersion: qlik.com/v1
kind: QlikSense
metadata:
name: contx1
labels:
version: v1.0.0
spec:
profile: docker-desktop
manifestsRoot: /Users/mqb/.qliksense/contexts/contx1/qlik-k8s/v0.0.1/manifests
storageClassName: efs
configs:
qliksense:
- name: acceptEULA
value: "yes"
`
ctx1Dir := filepath.Join(homeDir, "contexts", "contx1")
crFile := filepath.Join(ctx1Dir, "contx1.yaml")
os.MkdirAll(ctx1Dir, tempPermissionCode)
ioutil.WriteFile(crFile, []byte(cr), tempPermissionCode)
}
func TestGetCR(t *testing.T) {
td, dir := setup()
qc := NewQConfig(dir)
if qc.Spec.CurrentContext != "contx1" {
t.Fail()
}
// create CR
createCRFile(dir)
crFile := filepath.Join("contexts", "contx1", "contx1.yaml")
qct, e := qc.SetCrLocation("contx1", crFile)
if e != nil {
t.Fail()
t.Log(e)
}
qcr, err := qct.GetCurrentCR()
if err != nil {
t.Fail()
t.Log(err)
}
if qcr.Spec.Profile != "docker-desktop" {
t.Fail()
}
td()
}
func TestGetDecryptedCr(t *testing.T) {
td, dir := setup()
qc := NewQConfig(dir)
if qc.Spec.CurrentContext != "contx1" {
t.Fail()
}
// create CR
createCRFile(dir)
crFile := filepath.Join("contexts", "contx1", "contx1.yaml")
qct, e := qc.SetCrLocation("contx1", crFile)
if e != nil {
t.Fail()
t.Log(e)
}
qcr, err := qct.GetCurrentCR()
key, _ := setupGenerateKey(dir)
ecn, _ := EncryptData([]byte("mongodb://qlik-default-mongodb:27017/qliksense?ssl=false"), key)
b := b64.StdEncoding.EncodeToString(ecn)
qcr.Spec.AddToSecrets("qliksense", "mongodbUri", b, "")
qcr.SetFetchAccessToken("mytoken", key)
newCr, err := qct.GetDecryptedCr(qcr)
if err != nil {
t.Fail()
t.Log(err)
}
decryptedValue := newCr.Spec.GetFromSecrets("qliksense", "mongodbUri")
orignalValue := qcr.Spec.GetFromSecrets("qliksense", "mongodbUri")
if decryptedValue != "mongodb://qlik-default-mongodb:27017/qliksense?ssl=false" {
t.Fail()
b, _ := K8sToYaml(newCr)
t.Log(b)
}
if decryptedValue == orignalValue {
t.Fail()
}
if newCr.Spec.FetchSource.AccessToken != "mytoken" {
t.Fail()
}
td()
}
func setupGenerateKey(homeDir string) (string, error) {
secretKeyPairDir := filepath.Join(homeDir, "secrets", "contexts", "contx1", "secrets")
if err := os.MkdirAll(secretKeyPairDir, 0777); err != nil {
err = fmt.Errorf("Not able to create directories")
log.Fatal(err)
}
os.Setenv("QLIKSENSE_KEY_LOCATION", secretKeyPairDir)
key, _ := LoadSecretKey(secretKeyPairDir)
if key == "" {
return GenerateAndStoreSecretKey(secretKeyPairDir)
}
return key, nil
}
func Test_set_and_get_fetch_access_token(t *testing.T) {
td, homeDir := setup()
defer td()
createCRFile(homeDir)
crFile := filepath.Join("contexts", "contx1", "contx1.yaml")
qConfig := NewQConfig(homeDir)
newQ, _ := qConfig.SetCrLocation("contx1", crFile)
newQ.Write()
qConfig = NewQConfig(homeDir)
qcr, _ := qConfig.GetCurrentCR()
key, _ := qConfig.GetEncryptionKeyFor(qcr.GetName())
if err := qcr.SetFetchAccessToken("mytokenbeforeencryption", key); err != nil {
t.Log(err)
t.FailNow()
}
tok := qcr.GetFetchAccessToken(key)
if tok != "mytokenbeforeencryption" {
t.Log("Expected: mytokenbeforeencryption, got: " + tok)
t.Fail()
}
}

View File

@@ -1,728 +0,0 @@
package api
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/mitchellh/go-homedir"
appsv1 "k8s.io/api/apps/v1"
apiv1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/retry"
)
var gracePeriod int64 = 0
var waitTimeout = 2 * time.Minute
type ClientGoUtils struct {
Verbose bool
}
func (p *ClientGoUtils) LogVerboseMessage(strMessage string, args ...interface{}) {
if p.Verbose || os.Getenv("QLIKSENSE_DEBUG") == "true" {
fmt.Printf(strMessage, args...)
}
}
func int32Ptr(i int32) *int32 { return &i }
func (p *ClientGoUtils) LoadKubeConfigAndNamespace() (string, []byte, error) {
LogDebugMessage("Reading .kube/config file...")
homeDir, err := homedir.Dir()
if err != nil {
err = fmt.Errorf("Unable to deduce home dir")
return "", nil, err
}
LogDebugMessage("Kube config location: %s\n\n", filepath.Join(homeDir, ".kube", "config"))
kubeConfig := filepath.Join(homeDir, ".kube", "config")
kubeConfigContents, err := ioutil.ReadFile(kubeConfig)
if err != nil {
err = fmt.Errorf("Unable to deduce home dir")
return "", nil, err
}
// retrieve namespace
namespace := GetKubectlNamespace()
// if namespace comes back empty, we will run checks in the default namespace
if namespace == "" {
namespace = "default"
}
return namespace, kubeConfigContents, nil
}
func (p *ClientGoUtils) RetryOnError(mf func() error) error {
return retry.OnError(wait.Backoff{
Duration: 1 * time.Second,
Factor: 1,
Jitter: 0.1,
Steps: 5,
}, func(err error) bool {
return k8serrors.IsConflict(err) || k8serrors.IsGone(err) || k8serrors.IsServerTimeout(err) ||
k8serrors.IsServiceUnavailable(err) || k8serrors.IsTimeout(err) || k8serrors.IsTooManyRequests(err)
}, mf)
}
func (p *ClientGoUtils) GetK8SClientSet(kubeconfig []byte, contextName string) (*kubernetes.Clientset, *rest.Config, error) {
var clientConfig *rest.Config
var err error
if len(kubeconfig) == 0 {
clientConfig, err = rest.InClusterConfig()
if err != nil {
err = fmt.Errorf("Unable to load in-cluster kubeconfig: %w", err)
return nil, nil, err
}
} else {
config, err := clientcmd.Load(kubeconfig)
if err != nil {
err = fmt.Errorf("Unable to load kubeconfig: %w", err)
return nil, nil, err
}
if contextName != "" {
config.CurrentContext = contextName
}
clientConfig, err = clientcmd.NewDefaultClientConfig(*config, &clientcmd.ConfigOverrides{}).ClientConfig()
if err != nil {
err = fmt.Errorf("Unable to create client config from config: %w", err)
return nil, nil, err
}
}
clientset, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
err = fmt.Errorf("Unable to create clientset: %w", err)
return nil, nil, err
}
return clientset, clientConfig, nil
}
func (p *ClientGoUtils) CreatePreflightTestDeployment(clientset kubernetes.Interface, namespace string, depName string, imageName string) (*appsv1.Deployment, error) {
deploymentsClient := clientset.AppsV1().Deployments(namespace)
deployment := &appsv1.Deployment{
ObjectMeta: v1.ObjectMeta{
Name: depName,
},
Spec: appsv1.DeploymentSpec{
Replicas: int32Ptr(1),
Selector: &v1.LabelSelector{
MatchLabels: map[string]string{
"app": "preflight-check",
},
},
Template: apiv1.PodTemplateSpec{
ObjectMeta: v1.ObjectMeta{
Labels: map[string]string{
"app": "preflight-check",
"label": "preflight-check-label",
},
},
Spec: apiv1.PodSpec{
Containers: []apiv1.Container{
{
Name: "dep",
Image: imageName,
Ports: []apiv1.ContainerPort{
{
Name: "http",
Protocol: apiv1.ProtocolTCP,
ContainerPort: 80,
},
},
},
},
},
},
},
}
// Create Deployment
var result *appsv1.Deployment
if err := p.RetryOnError(func() (err error) {
result, err = deploymentsClient.Create(deployment)
return err
}); err != nil {
err = fmt.Errorf("unable to create deployments in the %s namespace: %w", namespace, err)
return nil, err
}
p.LogVerboseMessage("Created deployment %q\n", result.GetObjectMeta().GetName())
return deployment, nil
}
func (p *ClientGoUtils) getDeployment(clientset kubernetes.Interface, namespace, depName string) (*appsv1.Deployment, error) {
deploymentsClient := clientset.AppsV1().Deployments(namespace)
var deployment *appsv1.Deployment
if err := p.RetryOnError(func() (err error) {
deployment, err = deploymentsClient.Get(depName, v1.GetOptions{})
return err
}); err != nil {
err = fmt.Errorf("unable to get deployments in the %s namespace: %w", namespace, err)
LogDebugMessage("%v\n", err)
return nil, err
}
return deployment, nil
}
func (p *ClientGoUtils) DeleteDeployment(clientset kubernetes.Interface, namespace, name string) error {
deploymentsClient := clientset.AppsV1().Deployments(namespace)
// Create Deployment
deletePolicy := v1.DeletePropagationForeground
deleteOptions := v1.DeleteOptions{
PropagationPolicy: &deletePolicy,
GracePeriodSeconds: &gracePeriod,
}
if err := p.RetryOnError(func() (err error) {
return deploymentsClient.Delete(name, &deleteOptions)
}); err != nil {
return err
}
if err := p.WaitForDeploymentToDelete(clientset, namespace, name); err != nil {
return err
}
p.LogVerboseMessage("Deleted deployment: %s\n", name)
return nil
}
func (p *ClientGoUtils) CreatePreflightTestService(clientset kubernetes.Interface, namespace string, svcName string) (*apiv1.Service, error) {
iptr := int32Ptr(80)
servicesClient := clientset.CoreV1().Services(namespace)
service := &apiv1.Service{
ObjectMeta: v1.ObjectMeta{
Name: svcName,
Namespace: namespace,
Labels: map[string]string{
"app": "preflight-check",
},
},
Spec: apiv1.ServiceSpec{
Ports: []apiv1.ServicePort{
{Name: "port1",
Port: *iptr,
},
},
Selector: map[string]string{
"app": "preflight-check",
},
ClusterIP: "",
},
}
var result *apiv1.Service
if err := p.RetryOnError(func() (err error) {
result, err = servicesClient.Create(service)
return err
}); err != nil {
return nil, err
}
p.LogVerboseMessage("Created service %q\n", result.GetObjectMeta().GetName())
return service, nil
}
func (p *ClientGoUtils) GetService(clientset kubernetes.Interface, namespace, svcName string) (*apiv1.Service, error) {
servicesClient := clientset.CoreV1().Services(namespace)
var svc *apiv1.Service
if err := p.RetryOnError(func() (err error) {
svc, err = servicesClient.Get(svcName, v1.GetOptions{})
return err
}); err != nil {
err = fmt.Errorf("unable to get services in the %s namespace: %w", namespace, err)
return nil, err
}
return svc, nil
}
func (p *ClientGoUtils) DeleteService(clientset kubernetes.Interface, namespace, name string) error {
servicesClient := clientset.CoreV1().Services(namespace)
// Create Deployment
deletePolicy := v1.DeletePropagationForeground
deleteOptions := v1.DeleteOptions{
PropagationPolicy: &deletePolicy,
}
if err := p.RetryOnError(func() (err error) {
return servicesClient.Delete(name, &deleteOptions)
}); err != nil {
return err
}
p.LogVerboseMessage("Deleted service: %s\n", name)
return nil
}
func (p *ClientGoUtils) DeletePod(clientset kubernetes.Interface, namespace, name string) error {
podsClient := clientset.CoreV1().Pods(namespace)
deletePolicy := v1.DeletePropagationForeground
deleteOptions := v1.DeleteOptions{
PropagationPolicy: &deletePolicy,
GracePeriodSeconds: &gracePeriod,
}
if err := p.RetryOnError(func() (err error) {
return podsClient.Delete(name, &deleteOptions)
}); err != nil {
return err
}
if err := p.waitForPodToDelete(clientset, namespace, name); err != nil {
return err
}
p.LogVerboseMessage("Deleted pod: %s\n", name)
return nil
}
func (p *ClientGoUtils) CreatePreflightTestPod(clientset kubernetes.Interface, namespace, podName, imageName string, secretNames map[string]string, commandToRun []string) (*apiv1.Pod, error) {
// build the pod definition we want to deploy
pod := &apiv1.Pod{
ObjectMeta: v1.ObjectMeta{
Name: podName,
Namespace: namespace,
Labels: map[string]string{
"app": "preflight",
},
},
Spec: apiv1.PodSpec{
RestartPolicy: apiv1.RestartPolicyNever,
Containers: []apiv1.Container{
{
Name: "cnt",
Image: imageName,
ImagePullPolicy: apiv1.PullIfNotPresent,
Command: commandToRun,
},
},
},
}
if len(secretNames) > 0 {
for secretName, mountPath := range secretNames {
pod.Spec.Volumes = append(pod.Spec.Volumes, apiv1.Volume{
Name: secretName,
VolumeSource: apiv1.VolumeSource{
Secret: &apiv1.SecretVolumeSource{
SecretName: secretName,
Items: []apiv1.KeyToPath{
{
Key: secretName,
Path: filepath.Base(mountPath),
},
},
},
},
})
if len(pod.Spec.Containers) > 0 {
pod.Spec.Containers[0].VolumeMounts = append(pod.Spec.Containers[0].VolumeMounts, apiv1.VolumeMount{
Name: secretName,
MountPath: filepath.Dir(mountPath),
ReadOnly: true,
})
}
}
}
// now create the pod in kubernetes cluster using the clientset
if err := p.RetryOnError(func() (err error) {
pod, err = clientset.CoreV1().Pods(namespace).Create(pod)
return err
}); err != nil {
return nil, err
}
p.LogVerboseMessage("Created pod: %s\n", pod.Name)
return pod, nil
}
func (p *ClientGoUtils) getPod(clientset kubernetes.Interface, namespace, podName string) (*apiv1.Pod, error) {
LogDebugMessage("Fetching pod: %s\n", podName)
var pod *apiv1.Pod
if err := p.RetryOnError(func() (err error) {
pod, err = clientset.CoreV1().Pods(namespace).Get(podName, v1.GetOptions{})
return err
}); err != nil {
LogDebugMessage("%v\n", err)
return nil, err
}
return pod, nil
}
func (p *ClientGoUtils) GetPodLogs(clientset kubernetes.Interface, pod *apiv1.Pod) (string, error) {
return p.GetPodContainerLogs(clientset, pod, "")
}
func (p *ClientGoUtils) GetPodContainerLogs(clientset kubernetes.Interface, pod *apiv1.Pod, container string) (string, error) {
podLogOpts := apiv1.PodLogOptions{}
if container != "" {
podLogOpts.Container = container
}
LogDebugMessage("Retrieving logs for pod: %s namespace: %s\n", pod.GetName(), pod.Namespace)
req := clientset.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &podLogOpts)
podLogs, err := req.Stream()
if err != nil {
return "", err
}
defer podLogs.Close()
// time.Sleep(15 * time.Second)
buf := new(bytes.Buffer)
_, err = io.Copy(buf, podLogs)
if err != nil {
return "", err
}
LogDebugMessage("Log from pod: %s\n", buf.String())
return buf.String(), nil
}
func (p *ClientGoUtils) waitForResource(checkFunc func() (interface{}, error), validateFunc func(interface{}) bool) error {
timeout := time.NewTicker(waitTimeout)
defer timeout.Stop()
OUT:
for {
r, err := checkFunc()
if err != nil {
return err
}
select {
case <-timeout.C:
break OUT
default:
if validateFunc(r) {
break OUT
}
}
time.Sleep(5 * time.Second)
}
return nil
}
func (p *ClientGoUtils) WaitForDeployment(clientset kubernetes.Interface, namespace string, pfDeployment *appsv1.Deployment) error {
var err error
depName := pfDeployment.GetName()
checkFunc := func() (interface{}, error) {
pfDeployment, err = p.getDeployment(clientset, namespace, depName)
if err != nil {
err = fmt.Errorf("unable to retrieve deployment: %s\n", depName)
return nil, err
}
return pfDeployment, nil
}
validateFunc := func(data interface{}) bool {
d := data.(*appsv1.Deployment)
return int(d.Status.ReadyReplicas) > 0
}
if err := p.waitForResource(checkFunc, validateFunc); err != nil {
return err
}
if int(pfDeployment.Status.ReadyReplicas) == 0 {
err = fmt.Errorf("deployment took longer than expected to spin up pods")
return err
}
return nil
}
func (p *ClientGoUtils) WaitForPod(clientset kubernetes.Interface, namespace string, pod *apiv1.Pod) error {
var err error
if len(pod.Spec.Containers) == 0 {
err = fmt.Errorf("there are no containers in the pod")
return err
}
podName := pod.Name
checkFunc := func() (interface{}, error) {
pod, err = p.getPod(clientset, namespace, podName)
if err != nil {
err = fmt.Errorf("unable to retrieve %s pod by name", podName)
return nil, err
}
return pod, nil
}
validateFunc := func(data interface{}) bool {
po := data.(*apiv1.Pod)
return po.Status.Phase == apiv1.PodRunning || po.Status.Phase == apiv1.PodSucceeded || po.Status.Phase == apiv1.PodFailed
}
if err := p.waitForResource(checkFunc, validateFunc); err != nil {
return err
}
if pod.Status.Phase != apiv1.PodRunning && pod.Status.Phase != apiv1.PodSucceeded && pod.Status.Phase != apiv1.PodFailed {
err = fmt.Errorf("container is taking much longer than expected")
return err
}
return nil
}
func (p *ClientGoUtils) WaitForPodToDie(clientset kubernetes.Interface, namespace string, pod *apiv1.Pod) error {
podName := pod.Name
checkFunc := func() (interface{}, error) {
po, err := p.getPod(clientset, namespace, podName)
if err != nil {
err = fmt.Errorf("unable to retrieve %s pod by name", podName)
return nil, err
}
return po, nil
}
validateFunc := func(r interface{}) bool {
po := r.(*apiv1.Pod)
return po.Status.Phase == apiv1.PodFailed || po.Status.Phase == apiv1.PodSucceeded
}
if err := p.waitForResource(checkFunc, validateFunc); err != nil {
return err
}
return nil
}
func (p *ClientGoUtils) waitForPodToDelete(clientset kubernetes.Interface, namespace, podName string) error {
checkFunc := func() (interface{}, error) {
po, err := p.getPod(clientset, namespace, podName)
if err != nil {
return nil, err
}
return po, nil
}
validateFunc := func(po interface{}) bool {
return false
}
if err := p.waitForResource(checkFunc, validateFunc); err != nil {
return nil
}
err := fmt.Errorf("delete pod is taking unusually long")
return err
}
func (p *ClientGoUtils) WaitForDeploymentToDelete(clientset kubernetes.Interface, namespace, deploymentName string) error {
checkFunc := func() (interface{}, error) {
dep, err := p.getDeployment(clientset, namespace, deploymentName)
if err != nil {
return nil, err
}
return dep, nil
}
validateFunc := func(po interface{}) bool {
return false
}
if err := p.waitForResource(checkFunc, validateFunc); err != nil {
return nil
}
err := fmt.Errorf("delete deployment is taking unusually long")
return err
}
func (p *ClientGoUtils) CreatePreflightTestSecret(clientset kubernetes.Interface, namespace, secretName string, secretData []byte) (*apiv1.Secret, error) {
var secret *apiv1.Secret
var err error
// build the secret defination we want to create
secretSpec := &apiv1.Secret{
ObjectMeta: v1.ObjectMeta{
Name: secretName,
Namespace: namespace,
Labels: map[string]string{
"app": "preflight",
},
},
Data: map[string][]byte{
secretName: secretData,
},
}
// now create the secret in kubernetes cluster using the clientset
if err = p.RetryOnError(func() (err error) {
secret, err = clientset.CoreV1().Secrets(namespace).Create(secretSpec)
return err
}); err != nil {
return nil, err
}
p.LogVerboseMessage("Created Secret: %s\n", secret.Name)
return secret, nil
}
func (p *ClientGoUtils) DeleteK8sSecret(clientset kubernetes.Interface, namespace string, secretName string) error {
secretClient := clientset.CoreV1().Secrets(namespace)
deletePolicy := v1.DeletePropagationForeground
deleteOptions := v1.DeleteOptions{
PropagationPolicy: &deletePolicy,
}
err := secretClient.Delete(secretName, &deleteOptions)
if err != nil {
return err
}
p.LogVerboseMessage("Deleted Secret: %s\n", secretName)
return nil
}
func (p *ClientGoUtils) CreateStatefulSet(clientset kubernetes.Interface, namespace string, statefulSetName string, imageName string) (*appsv1.StatefulSet, error) {
statefulSetsClient := clientset.AppsV1().StatefulSets(namespace)
statefulset := &appsv1.StatefulSet{
ObjectMeta: v1.ObjectMeta{
Name: statefulSetName,
},
Spec: appsv1.StatefulSetSpec{
Replicas: int32Ptr(1),
Selector: &v1.LabelSelector{
MatchLabels: map[string]string{
"app": "postflight-check",
},
},
Template: apiv1.PodTemplateSpec{
ObjectMeta: v1.ObjectMeta{
Labels: map[string]string{
"app": "postflight-check",
"label": "postflight-check-label",
},
},
Spec: apiv1.PodSpec{
InitContainers: []apiv1.Container{
{
Name: "migration",
Image: "ubuntu",
ImagePullPolicy: apiv1.PullIfNotPresent,
// Command: []string{"bash", "-c", "for i in {1..10}; do echo \"from init container...\"; sleep 1; done"},
Command: []string{"bash", "-c", "for i in {1..10}; do echo \"from init container...\"; sleep 1; exit 1; done"},
},
},
Containers: []apiv1.Container{
{
Name: "statefulset",
Image: imageName,
Ports: []apiv1.ContainerPort{
{
Name: "http",
Protocol: apiv1.ProtocolTCP,
ContainerPort: 80,
},
},
},
},
},
},
},
}
// Create Statefulset
var result *appsv1.StatefulSet
if err := p.RetryOnError(func() (err error) {
result, err = statefulSetsClient.Create(statefulset)
return err
}); err != nil {
err = fmt.Errorf("unable to create statefulsets in the %s namespace: %w", namespace, err)
return nil, err
}
LogDebugMessage("Created statefulset %q\n", result.GetObjectMeta().GetName())
return statefulset, nil
}
func (p *ClientGoUtils) waitForStatefulSet(clientset kubernetes.Interface, namespace string, pfStatefulset *appsv1.StatefulSet) error {
var err error
statefulsetName := pfStatefulset.GetName()
checkFunc := func() (interface{}, error) {
pfStatefulset, err = p.getStatefulset(clientset, namespace, statefulsetName)
if err != nil {
err = fmt.Errorf("unable to retrieve stateful set: %s\n", statefulsetName)
return nil, err
}
return pfStatefulset, nil
}
validateFunc := func(data interface{}) bool {
s := data.(*appsv1.StatefulSet)
return int(s.Status.ReadyReplicas) > 0
}
if err := p.waitForResource(checkFunc, validateFunc); err != nil {
return err
}
if int(pfStatefulset.Status.ReadyReplicas) == 0 {
err = fmt.Errorf("deployment took longer than expected to spin up pods")
return err
}
return nil
}
func (p *ClientGoUtils) getStatefulset(clientset kubernetes.Interface, namespace, statefulsetName string) (*appsv1.StatefulSet, error) {
statefulsetsClient := clientset.AppsV1().StatefulSets(namespace)
var statefulset *appsv1.StatefulSet
if err := p.RetryOnError(func() (err error) {
statefulset, err = statefulsetsClient.Get(statefulsetName, v1.GetOptions{})
return err
}); err != nil {
err = fmt.Errorf("unable to get statefulsets in the %s namespace: %w", namespace, err)
fmt.Printf("%v\n", err)
return nil, err
}
return statefulset, nil
}
func (p *ClientGoUtils) deleteStatefulSet(clientset kubernetes.Interface, namespace, name string) error {
statefulsetClient := clientset.AppsV1().StatefulSets(namespace)
deletePolicy := v1.DeletePropagationForeground
deleteOptions := v1.DeleteOptions{
PropagationPolicy: &deletePolicy,
GracePeriodSeconds: &gracePeriod,
}
if err := p.RetryOnError(func() (err error) {
return statefulsetClient.Delete(name, &deleteOptions)
}); err != nil {
return err
}
if err := p.waitForStatefulsetToDelete(clientset, namespace, name); err != nil {
return err
}
LogDebugMessage("Deleted statefulset: %s\n", name)
return nil
}
func (p *ClientGoUtils) waitForStatefulsetToDelete(clientset kubernetes.Interface, namespace, statefulsetName string) error {
checkFunc := func() (interface{}, error) {
statefulset, err := p.getStatefulset(clientset, namespace, statefulsetName)
if err != nil {
return nil, err
}
return statefulset, nil
}
validateFunc := func(po interface{}) bool {
return false
}
if err := p.waitForResource(checkFunc, validateFunc); err != nil {
return nil
}
err := fmt.Errorf("delete statefulset is taking unusually long")
return err
}
func (p *ClientGoUtils) GetPodsAndPodLogsFromFailedInitContainer(clientset kubernetes.Interface, lbls map[string]string, namespace, containerName string) (map[string]string, error) {
set := labels.Set(lbls)
listOptions := v1.ListOptions{LabelSelector: set.AsSelector().String()}
podList, err := clientset.CoreV1().Pods(namespace).List(listOptions)
if err != nil {
err = fmt.Errorf("unable to get podlist: %v", err)
fmt.Printf("%s\n", err)
}
LogDebugMessage("%d Pods retrieved\n ", len(podList.Items))
// var logs map[string]string
logs := map[string]string{}
for _, pod := range podList.Items {
LogDebugMessage("pod: %v\n", pod.GetName())
LogDebugMessage("%d init containers retrieved\n", len(pod.Spec.InitContainers))
for _, cs := range pod.Status.InitContainerStatuses {
if cs.Name == containerName && ((cs.State.Terminated != nil && (cs.State.Terminated.Reason != "Completed" || cs.State.Terminated.ExitCode > 0)) ||
(cs.LastTerminationState.Terminated != nil && (cs.LastTerminationState.Terminated.Reason != "Completed" || cs.LastTerminationState.Terminated.ExitCode > 0))) {
logs[pod.GetName()], err = p.GetPodContainerLogs(clientset, &pod, cs.Name)
if err != nil {
err = fmt.Errorf("unable to get pod logs: %v", err)
fmt.Printf("%s\n", err)
return nil, err
}
}
}
}
return logs, nil
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,127 +0,0 @@
package api
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"github.com/qlik-oss/k-apis/pkg/config"
"k8s.io/apimachinery/pkg/runtime/schema"
machine_yaml "k8s.io/apimachinery/pkg/util/yaml"
)
const (
QliksenseConfigApiVersion = "v1"
QliksenseConfigApiGroup = "config.qlik.com"
QliksenseConfigKind = "QliksenseConfig"
QliksenseApiVersion = "v1"
QliksenseKind = "Qliksense"
QliksenseGroup = "qlik.com"
QliksenseDefaultProfile = "docker-desktop"
DefaultRotateKeys = "yes"
QliksenseMetadataName = "QliksenseConfigMetadata"
DefaultMongodbUri = "mongodb://qlik-default-mongodb:27017/qliksense?ssl=false"
DefaultMongodbUriKey = "mongodbUri"
)
// AddCommonConfig adds common configs into CRs
func (qliksenseCR *QliksenseCR) AddCommonConfig(contextName string) {
qliksenseCR.SetGroupVersionKind(schema.GroupVersionKind{
Group: QliksenseGroup,
Kind: QliksenseKind,
Version: QliksenseApiVersion,
})
qliksenseCR.SetName(contextName)
qliksenseCR.Spec = &config.CRSpec{
Profile: QliksenseDefaultProfile,
RotateKeys: DefaultRotateKeys,
}
qliksenseCR.Spec.AddToSecrets("qliksense", DefaultMongodbUriKey, DefaultMongodbUri, "")
}
// AddBaseQliksenseConfigs adds configs into config.yaml
func (qliksenseConfig *QliksenseConfig) AddBaseQliksenseConfigs(defaultQliksenseContext string) {
qliksenseConfig.SetGroupVersionKind(schema.GroupVersionKind{
Group: QliksenseConfigApiGroup,
Kind: QliksenseConfigKind,
Version: QliksenseConfigApiVersion,
})
qliksenseConfig.SetName(QliksenseMetadataName)
if defaultQliksenseContext != "" {
if qliksenseConfig.Spec == nil {
qliksenseConfig.Spec = &ContextSpec{}
}
qliksenseConfig.Spec.CurrentContext = defaultQliksenseContext
}
}
func (qliksenseConfig *QliksenseConfig) SwitchCurrentCRToVersionAndProfile(version, profile string) error {
if qcr, err := qliksenseConfig.GetCurrentCR(); err != nil {
return err
} else {
versionManifestRoot := qliksenseConfig.BuildCurrentManifestsRoot(version)
if (qcr.Spec.ManifestsRoot != versionManifestRoot) || (profile != "" && qcr.Spec.Profile != profile) || (qcr.GetLabelFromCr("version") != version) {
qcr.Spec.ManifestsRoot = versionManifestRoot
if profile != "" {
qcr.Spec.Profile = profile
}
qcr.AddLabelToCr("version", version)
if err := qliksenseConfig.WriteCurrentContextCR(qcr); err != nil {
return err
}
}
}
return nil
}
// WriteToFile (content, targetFile) writes content into specified file
func WriteToFile(content interface{}, targetFile string) error {
if content == nil || targetFile == "" {
return nil
}
x, err := K8sToYaml(content)
if err != nil {
err = fmt.Errorf("An error occurred during marshalling CR: %v", err)
log.Println(err)
return err
}
// Writing content
err = ioutil.WriteFile(targetFile, x, 0644)
if err != nil {
log.Println(err)
return err
}
LogDebugMessage("Wrote content into %s\n", targetFile)
return nil
}
// ReadFromFile (content, targetFile) reads content from specified sourcefile
func ReadFromFile(content interface{}, sourceFile string) error {
if content == nil || sourceFile == "" {
return nil
}
file, e := os.Open(sourceFile)
if e != nil {
return e
}
defer file.Close()
return ReadFromStream(content, file)
}
// ReadFromStream reads from input stream and creat yaml struct of type content
func ReadFromStream(content interface{}, reader io.Reader) error {
contents, err := ioutil.ReadAll(reader)
if err != nil {
err = fmt.Errorf("There was an error reading from reader: %v", err)
return err
}
// reading k8s style object
// https://stackoverflow.com/questions/44306554/how-to-deserialize-kubernetes-yaml-file
dec := machine_yaml.NewYAMLOrJSONDecoder(bytes.NewReader(contents), 10000)
return dec.Decode(content)
}

View File

@@ -1,103 +0,0 @@
package api
import (
"reflect"
"testing"
"github.com/qlik-oss/k-apis/pkg/config"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
testDir = "./tests"
)
func TestAddCommonConfig(t *testing.T) {
gvk := schema.GroupVersionKind{
Group: QliksenseGroup,
Kind: QliksenseKind,
Version: QliksenseApiVersion,
}
q := &QliksenseCR{}
q.SetName("myqliksense")
q.SetGroupVersionKind(gvk)
q.Spec = &config.CRSpec{
Profile: QliksenseDefaultProfile,
RotateKeys: DefaultRotateKeys,
Secrets: map[string]config.NameValues{
"qliksense": []config.NameValue{{
Name: DefaultMongodbUriKey,
Value: DefaultMongodbUri,
},
},
},
}
type args struct {
qliksenseCR *QliksenseCR
contextName string
}
tests := []struct {
name string
args args
want *QliksenseCR
}{
{
name: "valid case",
args: args{
qliksenseCR: &QliksenseCR{},
contextName: "myqliksense",
},
want: q,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.args.qliksenseCR.AddCommonConfig(tt.args.contextName)
if !reflect.DeepEqual(tt.args.qliksenseCR, tt.want) {
t.Errorf("AddCommonConfig() = %+v, want %+v", tt.args.qliksenseCR, tt.want)
}
})
}
}
func TestAddBaseQliksenseConfigs(t *testing.T) {
gvk := schema.GroupVersionKind{
Group: QliksenseConfigApiGroup,
Kind: QliksenseConfigKind,
Version: QliksenseConfigApiVersion,
}
qc := &QliksenseConfig{}
qc.SetGroupVersionKind(gvk)
qc.SetName(QliksenseMetadataName)
qc.Spec = &ContextSpec{
CurrentContext: "qlik-default",
}
type args struct {
qliksenseConfig *QliksenseConfig
defaultQliksenseContext string
}
tests := []struct {
name string
args args
want *QliksenseConfig
}{
{
name: "valid case",
args: args{
qliksenseConfig: &QliksenseConfig{},
defaultQliksenseContext: "qlik-default",
},
want: qc,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.args.qliksenseConfig.AddBaseQliksenseConfigs(tt.args.defaultQliksenseContext)
if !reflect.DeepEqual(tt.args.qliksenseConfig, tt.want) {
t.Errorf("AddBaseQliksenseConfigs() = %+v, want %+v", tt.args.qliksenseConfig, tt.want)
}
})
}
}

View File

@@ -1,8 +0,0 @@
package api
import "github.com/otiai10/copy"
//copy source directory to destination
func CopyDirectory(source string, dest string) error {
return copy.Copy(source, dest)
}

View File

@@ -1,101 +0,0 @@
package api
import (
"io/ioutil"
"os"
"path"
"path/filepath"
"testing"
kapis_git "github.com/qlik-oss/k-apis/pkg/git"
"sigs.k8s.io/kustomize/api/filesys"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/krusty"
"sigs.k8s.io/kustomize/api/types"
)
func TestCopyDirectory(t *testing.T) {
src, _ := ioutil.TempDir("", "")
f1, _ := ioutil.TempFile(src, "")
ioutil.TempFile(src, "")
dest, _ := ioutil.TempDir("", "")
CopyDirectory(src, dest)
if _, err := os.Lstat(filepath.Join(dest, filepath.Base(f1.Name()))); err != nil {
t.Log(err)
t.Fail()
}
}
func TestCopyDirectory_withGit_withKuz(t *testing.T) {
if testing.Short() {
t.Skip("Skipping in short test mode")
}
tmpDir1, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer os.RemoveAll(tmpDir1)
tmpDir2, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer os.RemoveAll(tmpDir2)
repoPath1 := path.Join(tmpDir1, "repo")
repo1, err := kapis_git.CloneRepository(repoPath1, "https://github.com/qlik-oss/qliksense-k8s", nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := CopyDirectory(repoPath1, tmpDir2); err != nil {
t.Fatalf("unexpected error: %v", err)
}
repoPath2 := tmpDir2
repo2, err := kapis_git.OpenRepository(repoPath2)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := kapis_git.Checkout(repo2, "v0.0.2", "", nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
repo2Manifest, err := kuz(path.Join(repoPath2, "manifests", "docker-desktop"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := kapis_git.Checkout(repo1, "v0.0.2", "", nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
repo1Manifest, err := kuz(path.Join(repoPath1, "manifests", "docker-desktop"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if string(repo2Manifest) != string(repo1Manifest) {
t.Logf("manifest generated on the original config:\n%v", string(repo1Manifest))
t.Logf("manifest generated on the copied config:\n%v", string(repo2Manifest))
t.Fatal("expected manifests to be equal, but they were not")
}
}
func kuz(directory string) ([]byte, error) {
options := &krusty.Options{
DoLegacyResourceSort: false,
LoadRestrictions: types.LoadRestrictionsNone,
DoPrune: false,
PluginConfig: konfig.DisabledPluginConfig(),
}
k := krusty.MakeKustomizer(filesys.MakeFsOnDisk(), options)
resMap, err := k.Run(directory)
if err != nil {
return nil, err
}
return resMap.AsYaml()
}

View File

@@ -1,103 +0,0 @@
package api
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type k8sDockerConfigJsonMapType struct {
Auths map[string]k8sDockerConfigJsonType `json:"auths"`
}
type k8sDockerConfigJsonType struct {
Username string `json:"username"`
Password string `json:"password"`
Email string `json:"email,omitempty"`
Auth string `json:"auth"`
}
func (kdcjt *k8sDockerConfigJsonType) GenerateAuth() {
kdcjt.Auth = base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", kdcjt.Username, kdcjt.Password)))
}
type DockerConfigJsonSecret struct {
Name string
Uri string
Username string
Password string
Email string
}
func (d *DockerConfigJsonSecret) ToYaml(encryptionKey string) ([]byte, error) {
k8sDockerConfigJson := k8sDockerConfigJsonType{
Username: d.Username,
Password: d.Password,
Email: d.Email,
}
k8sDockerConfigJson.GenerateAuth()
k8sDockerConfigJsonMap := k8sDockerConfigJsonMapType{
Auths: map[string]k8sDockerConfigJsonType{
d.Uri: k8sDockerConfigJson,
},
}
k8sDockerConfigJsonMapBytes, err := json.Marshal(k8sDockerConfigJsonMap)
if err != nil {
return nil, err
}
var k8sDockerConfigJsonMapMaybeEncryptedBytes []byte
if encryptionKey != "" {
if k8sDockerConfigJsonMapMaybeEncryptedBytes, err = EncryptData(k8sDockerConfigJsonMapBytes, encryptionKey); err != nil {
return nil, err
}
} else {
k8sDockerConfigJsonMapMaybeEncryptedBytes = k8sDockerConfigJsonMapBytes
}
k8sSecret := v1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: d.Name,
},
Type: v1.SecretTypeDockerConfigJson,
Data: map[string][]byte{
".dockerconfigjson": k8sDockerConfigJsonMapMaybeEncryptedBytes,
},
}
return K8sSecretToYaml(k8sSecret)
}
func (d *DockerConfigJsonSecret) FromYaml(secretBytes []byte, decryptionKey string) error {
k8sDockerConfigJsonMap := k8sDockerConfigJsonMapType{}
if k8sSecret, err := K8sSecretFromYaml(secretBytes); err != nil {
return err
} else if k8sSecret.TypeMeta.Kind != "Secret" {
return errors.New("not a Secret kind")
} else if k8sSecret.Type != v1.SecretTypeDockerConfigJson {
return errors.New("not a kubernetes.io/dockerconfigjson type")
} else if k8sDockerConfigJsonMapEncryptedBytes, ok := k8sSecret.Data[".dockerconfigjson"]; !ok {
return errors.New("secret data is missing a value for the .dockerconfigjson key")
} else if k8sDockerConfigJsonMapBytes, err := DecryptData(k8sDockerConfigJsonMapEncryptedBytes, decryptionKey); err != nil {
return errors.New("secret data is missing a value for the .dockerconfigjson key")
} else if err := json.Unmarshal(k8sDockerConfigJsonMapBytes, &k8sDockerConfigJsonMap); err != nil {
return err
} else {
d.Name = k8sSecret.ObjectMeta.Name
for registry, k8sDockerConfigJson := range k8sDockerConfigJsonMap.Auths {
d.Uri = registry
d.Username = k8sDockerConfigJson.Username
d.Password = k8sDockerConfigJson.Password
d.Email = k8sDockerConfigJson.Email
break
}
return nil
}
}

View File

@@ -1,69 +0,0 @@
package api
import (
"encoding/base64"
"encoding/json"
"fmt"
"reflect"
"testing"
"gopkg.in/yaml.v2"
)
func TestDockerConfigJsonSecret(t *testing.T) {
dockerConfigJsonSecret := DockerConfigJsonSecret{
Name: "some-name",
Uri: "some-uri",
Username: "some-username",
Password: "some-password",
Email: "some-email",
}
dockerConfigJsonSecretFromYaml := DockerConfigJsonSecret{}
validYamlMap := map[string]interface{}{}
encryptionKey, err := GenerateKey()
if err != nil {
t.Fatalf("error generating RSA private key: %v\n", err)
}
dockerConfigJsonSecretYamlBytes, err := dockerConfigJsonSecret.ToYaml(encryptionKey)
dockerConfigJsonMap := map[string]interface{}{}
if err != nil {
t.Fatalf("error converting secret to yaml: %v", err)
} else if err := yaml.Unmarshal(dockerConfigJsonSecretYamlBytes, &validYamlMap); err != nil {
t.Fatalf("error unmarshalling yaml string: %v, error: %v", string(dockerConfigJsonSecretYamlBytes), err)
} else if validYamlMap["apiVersion"] != "v1" ||
validYamlMap["kind"] != "Secret" ||
validYamlMap["metadata"].(map[interface {}]interface {})["name"] != dockerConfigJsonSecret.Name ||
validYamlMap["type"] != "kubernetes.io/dockerconfigjson" {
t.Fatalf("error verifying validity of secret yaml: %v", string(dockerConfigJsonSecretYamlBytes))
} else if dockerConfigJsonBytesBase64, ok := validYamlMap["data"].(map[interface {}]interface {})[".dockerconfigjson"]; !ok {
t.Fatalf("no .dockerconfigjson data key in the secret yaml: %v", string(dockerConfigJsonSecretYamlBytes))
} else if dockerConfigJsonEncryptedBytes, err := base64.StdEncoding.DecodeString(dockerConfigJsonBytesBase64.(string)); err != nil {
t.Fatalf("error decoding dockerConfigJsonBytes from base64: %v", err)
} else if dockerConfigJsonBytes, err := DecryptData(dockerConfigJsonEncryptedBytes, encryptionKey); err != nil {
t.Fatalf("error decrypting dockerConfigJsonBytes: %v", err)
} else if err := json.Unmarshal(dockerConfigJsonBytes, &dockerConfigJsonMap); err != nil {
t.Fatalf("error unmarshalling dockerConfigJson from json: %v", err)
} else if dockerConfigJson, ok := dockerConfigJsonMap["auths"].(map[string]interface {})[dockerConfigJsonSecret.Uri]; !ok {
t.Fatalf("dockerConfigJson map does not contain data for the registry: %v", dockerConfigJsonSecret.Uri)
} else if dockerConfigJson.(map[string]interface {})["username"] != dockerConfigJsonSecret.Username ||
dockerConfigJson.(map[string]interface {})["password"] != dockerConfigJsonSecret.Password ||
dockerConfigJson.(map[string]interface {})["email"] != dockerConfigJsonSecret.Email {
t.Fatal("dockerConfigJson map does not contain expected values")
} else {
authBase64 := dockerConfigJson.(map[string]interface {})["auth"]
if auth, err := base64.StdEncoding.DecodeString(authBase64.(string)); err != nil {
t.Fatal("error base64 decoding auth value")
} else if string(auth) != fmt.Sprintf("%s:%s", dockerConfigJsonSecret.Username, dockerConfigJsonSecret.Password) {
t.Fatal("auth value was not what we expected")
}
}
t.Logf("dockerConfigJsonSecretYaml: \n%v\n", string(dockerConfigJsonSecretYamlBytes))
if err := dockerConfigJsonSecretFromYaml.FromYaml(dockerConfigJsonSecretYamlBytes, encryptionKey); err != nil {
t.Fatalf("error reading secret in from yaml: %v", err)
} else if !reflect.DeepEqual(dockerConfigJsonSecret, dockerConfigJsonSecretFromYaml) {
t.Fatalf("secret: %v does not equal secret: %v", dockerConfigJsonSecret, dockerConfigJsonSecretFromYaml)
}
}

View File

@@ -1,102 +0,0 @@
package api
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"path/filepath"
)
const (
key_file_name = "user_secret_key"
)
// GenerateAndStoreSecretKey generates and stores key
func GenerateAndStoreSecretKey(secretsDir string) (string, error) {
// creating contexts/qlik-default/secrets/user_secret_key
keyFile := filepath.Join(secretsDir, key_file_name)
key, err := GenerateKey()
if err != nil {
return "", err
}
if err := writeContentToFile([]byte(key), keyFile); err != nil {
return "", err
}
return key, nil
}
func LoadSecretKey(secretsDir string) (string, error) {
keyFile := filepath.Join(secretsDir, key_file_name)
by, err := ioutil.ReadFile(keyFile)
if err != nil {
return "", err
}
return string(by), nil
}
// writeContentToFile writes keys to a file
func writeContentToFile(keyData []byte, fileName string) error {
err := ioutil.WriteFile(fileName, keyData, 0600)
if err != nil {
log.Printf("error writing to file (%s): %v", fileName, err)
return err
}
return nil
}
func GenerateKey() (string, error) {
salt := make([]byte, 32)
if _, err := rand.Read(salt); err != nil {
return "", err
}
s := fmt.Sprintf("%x", salt)
return s, nil
}
func EncryptData(plaintext []byte, userKey string) ([]byte, error) {
key, _ := hex.DecodeString(userKey)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, aesgcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return aesgcm.Seal(nonce, nonce, plaintext, nil), nil
}
func DecryptData(ciphertext []byte, userKey string) ([]byte, error) {
key, _ := hex.DecodeString(userKey)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := aesgcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, errors.New("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}

View File

@@ -1,29 +0,0 @@
package api
import (
"testing"
)
func Test_encrypt_decrypt(t *testing.T) {
key, err := GenerateKey()
if err != nil {
t.Log(err)
t.FailNow()
}
testData := "this is a secret value"
enc, err := EncryptData([]byte(testData), key)
if err != nil {
t.Log(err)
t.FailNow()
}
dec, err := DecryptData(enc, key)
if err != nil {
t.Log(err)
t.FailNow()
}
if testData != string(dec) {
t.Log("expected: " + testData)
t.Log("actual: " + string(dec))
t.Fail()
}
}

View File

@@ -1,30 +0,0 @@
package api
import (
v1 "k8s.io/api/core/v1"
"sigs.k8s.io/yaml"
)
func K8sSecretToYaml(k8sSecret v1.Secret) ([]byte, error) {
return K8sToYaml(k8sSecret)
}
func K8sSecretFromYaml(k8sSecretBytes []byte) (v1.Secret, error) {
k8sSecret := v1.Secret{}
if err := yaml.UnmarshalStrict(k8sSecretBytes, &k8sSecret); err != nil {
return k8sSecret, err
}
return k8sSecret, nil
}
func K8sToYaml(k8sObj interface{}) ([]byte, error) {
k8sSecretYamlMap := map[string]interface{}{}
if k8sSecretYamlBytes, err := yaml.Marshal(k8sObj); err != nil {
return nil, err
} else if err := yaml.Unmarshal(k8sSecretYamlBytes, &k8sSecretYamlMap); err != nil {
return nil, err
} else {
delete(k8sSecretYamlMap["metadata"].(map[string]interface{}), "creationTimestamp")
return yaml.Marshal(k8sSecretYamlMap)
}
}

View File

@@ -1,134 +0,0 @@
package api
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
)
// KubectlApply create resources in the provided namespace,
// if namespace="" then use whatever the kubectl default is
func KubectlApply(manifests, namespace string) error {
return kubectlOperation(manifests, "apply", namespace)
}
func KubectlApplyVerbose(manifests, namespace string, verbose bool) error {
return kubectlOperationVerbose(manifests, "apply", namespace, verbose)
}
// KubectlDelete delete resources in the provided namespace,
// if namespace="" then use whatever the kubectl default is
func KubectlDelete(manifests, namespace string) error {
return kubectlOperation(manifests, "delete", namespace)
}
func KubectlDeleteVerbose(manifests, namespace string, verbose bool) error {
return kubectlOperationVerbose(manifests, "delete", namespace, verbose)
}
func GetKubectlNamespace() string {
namespace := ""
cmd := exec.Command("kubectl", "config", "current-context")
var out, out2 bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
fmt.Printf("kubectl config current-context %q\n", err)
return namespace
}
if out.String() == "" {
fmt.Println("kubectl config current-context does not return anything")
return namespace
}
cmd = exec.Command("kubectl", "config", "view", "-o", `jsonpath={.contexts[?(@.name == "`+strings.TrimSpace(out.String())+`")].context.namespace}`)
cmd.Stdout = &out2
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
fmt.Printf("kubectl config view failed with %q\n", err)
return namespace
}
namespace = out2.String()
return namespace
}
func SetKubectlNamespace(ns string) {
cmd := exec.Command("kubectl", "config", "set-context", "--namespace="+ns, "--current")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
fmt.Printf("kubectl config set-context --namespace failed with %q\n", err)
}
}
func kubectlOperation(manifests string, oprName string, namespace string) error {
return kubectlOperationVerbose(manifests, oprName, namespace, true)
}
func kubectlOperationVerbose(manifests string, oprName string, namespace string, verbose bool) error {
tempYaml, err := ioutil.TempFile("", "")
if err != nil {
fmt.Println("cannot create file ", err)
return err
}
tempYaml.WriteString(manifests)
arguments := make([]string, 0)
arguments = append(arguments, oprName)
arguments = append(arguments, "-f")
arguments = append(arguments, tempYaml.Name())
if oprName == "apply" {
arguments = append(arguments, "--validate=false")
}
if namespace != "" {
arguments = append(arguments, "-n")
arguments = append(arguments, namespace)
}
var cmd *exec.Cmd
if oprName == "apply" {
cmd = exec.Command("kubectl", arguments...)
} else {
cmd = exec.Command("kubectl", arguments...)
}
sterrBuffer := &bytes.Buffer{}
stoutBuffer := &bytes.Buffer{}
cmd.Stdout = stoutBuffer
cmd.Stderr = sterrBuffer
err = cmd.Run()
if err != nil {
return fmt.Errorf("kubectl %v failed with: %v, %v, temp k8s yaml file:%v\n", oprName, err, sterrBuffer.String(), tempYaml.Name())
}
if verbose {
fmt.Println(stoutBuffer.String())
}
os.Remove(tempYaml.Name())
return nil
}
func KubectlDirectOps(opr []string, namespace string) (string, error) {
arguments := []string{}
if namespace != "" {
arguments = append(arguments, "-n", namespace)
}
arguments = append(arguments, opr...)
var out bytes.Buffer
cmd := exec.Command("kubectl", arguments...)
LogDebugMessage("Kubectl command: %s %v\n", "kubectl", arguments)
sterrBuffer := &bytes.Buffer{}
cmd.Stderr = sterrBuffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("kubectl %v failed with: %v, %v\n", opr, err, sterrBuffer.String())
}
s := out.String()
return s, nil
}

View File

@@ -1,32 +0,0 @@
package api
import (
"fmt"
"strings"
"testing"
)
func TestGetKubectlNamespace(t *testing.T) {
t.Skip()
ns := GetKubectlNamespace()
SetKubectlNamespace("tada")
got := GetKubectlNamespace()
if got != "tada" {
t.Log(got)
t.Fail()
}
SetKubectlNamespace(ns)
}
func TestKubectlDirectOps(t *testing.T) {
t.Skip()
SetKubectlNamespace("test")
ns := GetKubectlNamespace()
opr := fmt.Sprintf("version")
opr1 := strings.Fields(opr)
_, err := KubectlDirectOps(opr1, ns)
if err != nil {
t.Log(err)
t.Fail()
}
}

View File

@@ -1,138 +0,0 @@
package api
import (
"os"
"path"
"path/filepath"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type PreflightConfig struct {
metav1.TypeMeta `json:",inline" yaml:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty"`
Spec *PreflightSpec `json:"spec" yaml:"spec"`
QliksenseHomePath string `json:"-" yaml:"-"`
}
type PreflightSpec struct {
MinK8sVersion string `json:"minK8sVersion,omitempty" yaml:"minK8sVersion,omitempty"`
MinMongoVersion string `json:"minMongoVersion,omitempty" yaml:"minMongoVersion,omitempty"`
Images map[string]string `json:"images,omitempty" yaml:"images,omitempty"`
}
//NewPreflightConfigEmpty create empty PreflightConfig object
func NewPreflightConfigEmpty(qHome string) *PreflightConfig {
p := &PreflightConfig{
QliksenseHomePath: qHome,
TypeMeta: metav1.TypeMeta{
APIVersion: "config.qlik.com/v1",
Kind: "PreflightConfig",
},
ObjectMeta: metav1.ObjectMeta{
Name: "PreflightConfigMetadata",
},
Spec: &PreflightSpec{},
}
return p
}
//NewPreflightConfig create empty PreflightConfig object if preflit/preflight-config.yaml not exist
func NewPreflightConfig(qHome string) *PreflightConfig {
p := NewPreflightConfigEmpty(qHome)
conFile := p.GetConfigFilePath()
if _, err := os.Lstat(conFile); err != nil {
return p
}
p = &PreflightConfig{
QliksenseHomePath: qHome,
}
if err := ReadFromFile(p, conFile); err != nil {
return nil
}
return p
}
//GetConfigFilePath return preflight-config.yaml file path
func (p *PreflightConfig) GetConfigFilePath() string {
return filepath.Join(p.QliksenseHomePath, "preflight", "preflight-config.yaml")
}
//Write write PreflightConfig object into the ~/.qliksense/preflight/preflight-config.yaml file
func (p *PreflightConfig) Write() error {
pDir := filepath.Join(p.QliksenseHomePath, "preflight")
if err := os.MkdirAll(pDir, os.ModePerm); err != nil {
return err
}
return WriteToFile(p, p.GetConfigFilePath())
}
func (p *PreflightConfig) AddMinK8sV(version string) {
if p.Spec == nil {
p.Spec = &PreflightSpec{}
}
p.Spec.MinK8sVersion = version
}
func (p *PreflightConfig) AddMinMongoV(version string) {
if p.Spec == nil {
p.Spec = &PreflightSpec{}
}
p.Spec.MinMongoVersion = version
}
func (p *PreflightConfig) AddImage(imageFor, imageName string) {
if p.Spec.Images == nil {
p.Spec.Images = make(map[string]string)
}
p.Spec.Images[imageFor] = imageName
}
func (p *PreflightConfig) GetImageName(imageFor string, accountForImageRegistry bool) (string, error) {
if p.Spec.Images == nil {
return "", nil
}
image := p.Spec.Images[imageFor]
if accountForImageRegistry {
qConfig := NewQConfig(p.QliksenseHomePath)
if currentCR, err := qConfig.GetCurrentCR(); err != nil {
return "", err
} else if imageRegistry := currentCR.Spec.GetImageRegistry(); imageRegistry != "" {
imageSegments := strings.Split(image, "/")
imageNameAndTag := imageSegments[len(imageSegments)-1]
return path.Join(imageRegistry, imageNameAndTag), nil
}
}
return image, nil
}
func (p *PreflightConfig) GetMinK8sVersion() string {
return p.Spec.MinK8sVersion
}
func (p *PreflightConfig) GetMinMongoVersion() string {
return p.Spec.MinMongoVersion
}
func (p *PreflightConfig) IsExistOnDisk() bool {
if _, err := os.Lstat(p.GetConfigFilePath()); err != nil {
return false
}
return true
}
func (p *PreflightConfig) GetImageMap() map[string]string {
return p.Spec.Images
}
func (p *PreflightConfig) Initialize() error {
if p.IsExistOnDisk() {
return nil
}
p.AddMinK8sV("1.15")
p.AddMinMongoV("3.6")
p.AddImage("nginx", "nginx")
p.AddImage("netcat", "subfuzion/netcat")
p.AddImage("preflight-mongo", "qlik-docker-oss.bintray.io/preflight-mongo")
return p.Write()
}

View File

@@ -1,138 +0,0 @@
package api
import (
"fmt"
"io/ioutil"
"os"
"path"
"testing"
)
func Test_Initalize(t *testing.T) {
testCases := []struct {
name string
validate func(t *testing.T, tempDir string)
}{
{
name: "without account for imageRegistry",
validate: func(t *testing.T, tempDir string) {
preflightConfig := NewPreflightConfig(tempDir)
imageName, err := preflightConfig.GetImageName("test", false)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if imageName != "testimage" {
t.Fatalf("expected image name: testimage, got: %v", imageName)
}
},
},
{
name: "with account for configured imageRegistry",
validate: func(t *testing.T, tempDir string) {
registry := "registryFoo"
setupQliksenseTestDefaultContext(t, tempDir, fmt.Sprintf(`
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
spec:
configs:
qliksense:
- name: imageRegistry
value: %v
`, registry))
preflightConfig := NewPreflightConfig(tempDir)
imageName, err := preflightConfig.GetImageName("test", true)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expectedImageName := fmt.Sprintf("%v/testimage", registry)
if imageName != expectedImageName {
t.Fatalf("expected image name: %v, got: %v", expectedImageName, imageName)
}
},
},
{
name: "with account for un-configured imageRegistry",
validate: func(t *testing.T, tempDir string) {
setupQliksenseTestDefaultContext(t, tempDir, `
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
spec:
configs:
qliksense:
- name: something
value: other
`)
preflightConfig := NewPreflightConfig(tempDir)
imageName, err := preflightConfig.GetImageName("test", true)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expectedImageName := "testimage"
if imageName != expectedImageName {
t.Fatalf("expected image name: %v, got: %v", expectedImageName, imageName)
}
},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
tempDir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
setupPreflightConfig(t, tempDir)
testCase.validate(t, tempDir)
})
}
}
func setupPreflightConfig(t *testing.T, tempDir string) {
pf := NewPreflightConfig(tempDir)
if err := pf.Initialize(); err != nil {
t.Fatal(err)
}
p := &PreflightConfig{
QliksenseHomePath: tempDir,
}
if err := ReadFromFile(p, pf.GetConfigFilePath()); err != nil {
t.Fatal(err)
}
if p.GetMinK8sVersion() != "1.15" {
t.Fatalf("expected k8 version: 1.15, but got " + p.GetMinK8sVersion())
}
p.AddImage("test", "testimage")
if err := p.Write(); err != nil {
t.Fatal(err)
}
}
func setupQliksenseTestDefaultContext(t *testing.T, tmpQlikSenseHome, CR string) {
if err := ioutil.WriteFile(path.Join(tmpQlikSenseHome, "config.yaml"), []byte(`
apiVersion: config.qlik.com/v1
kind: QliksenseConfig
metadata:
name: QliksenseConfigMetadata
spec:
contexts:
- name: qlik-default
crFile: contexts/qlik-default/qlik-default.yaml
currentContext: qlik-default
`), os.ModePerm); err != nil {
t.Fatalf("unexpected error: %v", err)
}
defaultContextDir := path.Join(tmpQlikSenseHome, "contexts", "qlik-default")
if err := os.MkdirAll(defaultContextDir, os.ModePerm); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := ioutil.WriteFile(path.Join(defaultContextDir, "qlik-default.yaml"), []byte(CR), os.ModePerm); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}

View File

@@ -1,49 +0,0 @@
package api
import (
kapi_config "github.com/qlik-oss/k-apis/pkg/config"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// QliksenseConfig is exported
type QliksenseConfig struct {
metav1.TypeMeta `json:",inline" yaml:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty"`
Spec *ContextSpec `json:"spec" yaml:"spec"`
QliksenseHomePath string `json:"-" yaml:"-"`
}
/*type CommonConfig struct {
metav1.TypeMeta `json:",inline" yaml:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty"`
}
*/
// QliksenseCR is exported
type QliksenseCR struct {
kapi_config.KApiCr `json:",inline" yaml:",inline"`
}
// ContextSpec is exported
type ContextSpec struct {
Contexts []Context `json:"contexts" yaml:"contexts"`
CurrentContext string `json:"currentContext" yaml:"currentContext"`
}
// Context is exported
type Context struct {
Name string `json:"name,omitempty" yaml:"name,omitempty"`
CrFile string `json:"crFile,omitempty" yaml:"crFile,omitempty"`
}
// Metadata is exported
type Metadata struct {
Name string `json:"name,omitempty" yaml:"name,omitempty"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
}
// ServiceKeyValue holds the combination of service, key and value
type ServiceKeyValue struct {
SvcName string
Key string
Value string
}

View File

@@ -1,299 +0,0 @@
package api
import (
"archive/tar"
"archive/zip"
"compress/gzip"
b64 "encoding/base64"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/pkg/errors"
)
func checkExists(filename string) os.FileInfo {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return nil
}
LogDebugMessage("File exists\n")
return info
}
// FileExists checks if a file exists
func FileExists(filename string) bool {
if fe := checkExists(filename); fe != nil && !fe.IsDir() {
return true
}
return false
}
// DirExists checks if a directory exists
func DirExists(dirname string) bool {
if fe := checkExists(dirname); fe != nil && fe.IsDir() {
return true
}
return false
}
// LogDebugMessage logs a debug message
func LogDebugMessage(strMessage string, args ...interface{}) {
if os.Getenv("QLIKSENSE_DEBUG") == "true" {
fmt.Printf(strMessage, args...)
}
}
// ReadKeys reads key file from disk
func ReadKeys(keyFile string) ([]byte, error) {
keybyteArray, err := ioutil.ReadFile(keyFile)
if err != nil {
err = fmt.Errorf("There was an error reading from file: %s, %v", keyFile, err)
log.Println(err)
return nil, err
}
return keybyteArray, nil
}
// ProcessConfigArgs processes args and returns an service, key, value slice
func ProcessConfigArgs(args []string, base64Encoded bool) ([]*ServiceKeyValue, error) {
// prepare received args
// split args[0] into key and value
if len(args) == 0 {
err := fmt.Errorf("No args were provided. Please provide args to configure the current context")
return nil, err
}
notValidErr := fmt.Errorf("Please provide valid args for this command")
resultSvcKV := make([]*ServiceKeyValue, len(args))
// qliksense.mongodb=somethig
for i, arg := range args {
LogDebugMessage("Arg received: %s\n", arg)
first := strings.SplitN(arg, "=", 2)
if len(first) != 2 {
return nil, notValidErr
}
svcKey := getSvcAndKey(first[0])
if len(svcKey) != 2 {
return nil, notValidErr
}
resultValue := strings.Trim(first[1], "\"")
if base64Encoded {
if decodeByte, err := b64.StdEncoding.DecodeString(resultValue); err != nil {
return nil, err
} else {
resultValue = strings.Trim(string(decodeByte), "\n ")
}
}
resultSvcKV[i] = &ServiceKeyValue{
SvcName: svcKey[0],
Key: svcKey[1],
Value: resultValue,
}
}
return resultSvcKV, nil
}
// input should be svc[key]
func getSvcAndKey(arg string) []string {
// for key
re := regexp.MustCompile(`\[(.*)\]`)
// for service
re2 := regexp.MustCompile(`(.*)\[`)
keys := re.FindStringSubmatch(arg)
svcs := re2.FindStringSubmatch(arg)
if len(svcs) != 2 || len(keys) != 2 {
return strings.SplitN(arg, ".", 2)
}
if svcs[1] == "" || keys[1] == "" {
return []string{}
}
return []string{svcs[1], keys[1]}
}
func ExecuteTaskWithBlinkingStdoutFeedback(task func() (interface{}, error), feedback string) (result interface{}, err error) {
taskDone := make(chan bool)
go func() {
result, err = task()
taskDone <- true
}()
progressOnTicker := time.NewTicker(500 * time.Millisecond)
progressOffTicker := time.NewTicker(1000 * time.Millisecond)
printProgress := func(on bool) {
if on {
fmt.Printf("%s\r", feedback)
} else {
fmt.Printf("%s\r", strings.Repeat(" ", len(feedback)))
}
}
for {
select {
case <-taskDone:
progressOnTicker.Stop()
progressOffTicker.Stop()
printProgress(false)
return result, err
case <-progressOnTicker.C:
printProgress(true)
case <-progressOffTicker.C:
printProgress(false)
}
}
}
func DownloadFile(url, baseFolder, installerName string) error {
var (
out *os.File
err error
resp *http.Response
)
// Create the file
fileName := filepath.Join(baseFolder, installerName)
LogDebugMessage("Installer Filename: %s\n", fileName)
if out, err = os.Create(fileName); err != nil {
return err
}
defer out.Close()
// Get the data
if resp, err = http.Get(url); err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("unable to download the file from URL: %s, status: %s", url, resp.Status)
log.Println(err)
return err
}
// Write the body to file
if _, err = io.Copy(out, resp.Body); err != nil {
return err
}
err = os.Chmod(fileName, os.ModePerm)
if err != nil {
log.Println(err)
}
return nil
}
func ExplodePackage(destination, fileToUntar string) error {
LogDebugMessage("Destination: %s\n", destination)
LogDebugMessage("fileToUntar: %s\n", fileToUntar)
if strings.HasSuffix(fileToUntar, "zip") {
LogDebugMessage("This is a windows file : %s", fileToUntar)
err := UnZipFile(destination, fileToUntar)
if err != nil {
return nil
}
} else if strings.HasSuffix(fileToUntar, "tar.gz") {
LogDebugMessage("This is a mac/linux file: %s", fileToUntar)
err := UntarGzFile(destination, fileToUntar)
if err != nil {
return nil
}
}
return nil
}
func UntarGzFile(destination, fileToUntar string) error {
lFile, err := os.Open(fileToUntar)
if err != nil {
err = errors.Wrapf(err, "unable to read the local file %s", fileToUntar)
log.Fatal(err)
return err
}
gzReader, err := gzip.NewReader(lFile)
if err != nil {
err = errors.Wrap(err, "unable to load the file into a gz reader")
log.Fatal(err)
return err
}
defer gzReader.Close()
tarReader := tar.NewReader(gzReader)
for {
header, err := tarReader.Next()
switch {
case err == io.EOF:
return nil
case err != nil:
err = errors.Wrap(err, "error during untar")
log.Fatal(err)
return err
case header == nil:
continue
}
fileInLoop := filepath.Join(destination, header.Name)
switch header.Typeflag {
case tar.TypeDir:
if _, err := os.Stat(fileInLoop); err != nil {
if err := os.MkdirAll(fileInLoop, 0755); err != nil {
err = errors.Wrapf(err, "error creating directory %s", fileInLoop)
log.Fatal(err)
return err
}
}
case tar.TypeReg:
fileAtLoc, err := os.OpenFile(fileInLoop, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
if err != nil {
err = errors.Wrapf(err, "error opening file %s", fileInLoop)
log.Fatal(err)
return err
}
if _, err := io.Copy(fileAtLoc, tarReader); err != nil {
err = errors.Wrapf(err, "error writing file %s", fileInLoop)
log.Fatal(err)
return err
}
fileAtLoc.Close()
fileAtLoc.Chmod(os.ModePerm)
}
}
}
func UnZipFile(destination, fileToUnzip string) error {
zipReader, _ := zip.OpenReader(fileToUnzip)
for _, file := range zipReader.Reader.File {
zippedFile, err := file.Open()
if err != nil {
log.Fatal(err)
}
defer zippedFile.Close()
extractedFilePath := filepath.Join(
destination,
file.Name,
)
outputFile, err := os.OpenFile(
extractedFilePath,
os.O_WRONLY|os.O_CREATE|os.O_TRUNC,
file.Mode(),
)
if err != nil {
log.Fatal(err)
}
defer outputFile.Close()
_, err = io.Copy(outputFile, zippedFile)
if err != nil {
log.Fatal(err)
}
LogDebugMessage("File extracted: %s, Extracted file path: %s\n", file.Name, extractedFilePath)
}
return nil
}

View File

@@ -1,68 +0,0 @@
package api
import (
"testing"
)
func TestProcessConfigArgs(t *testing.T) {
args := []string{
"qliksense.mongodb=mongouri://something?ffall",
"test_under.test=value_under",
"test-dash.dash-key=value-dash",
"test-dot.dot-key=127.0.0.1",
"test123.key123=value123",
"test-equal.keyequal=newvalue=@hj",
}
expectedKeys := []string{"mongodb", "test", "dash-key", "dot-key", "key123", "keyequal"}
expectedValue := []string{"mongouri://something?ffall", "value_under", "value-dash", "127.0.0.1", "value123", "newvalue=@hj"}
exppectedSvc := []string{"qliksense", "test_under", "test-dash", "test-dot", "test123", "test-equal"}
sv, err := ProcessConfigArgs(args, false)
if err != nil {
t.Log(err)
t.FailNow()
}
for _, v := range sv {
if !contains(expectedKeys, v.Key) {
t.Fail()
t.Log("expectd key " + v.Key + " not found")
}
if !contains(expectedValue, v.Value) {
t.Fail()
t.Log("expectd Value " + v.Value + " not found")
}
if !contains(exppectedSvc, v.SvcName) {
t.Fail()
t.Log("expectd service " + v.SvcName + " not found")
}
}
}
func contains(arr []string, str string) bool {
for _, a := range arr {
if a == str {
return true
}
}
return false
}
func TestGetSvcAndKey(t *testing.T) {
s1 := "qliksense[tls.cert]"
sa := getSvcAndKey(s1)
if sa[0] != "qliksense" || sa[1] != "tls.cert" {
t.Fail()
t.Logf("expected service: qliksense but got %s", sa[0])
t.Logf("expected key: tls.cert but got %s", sa[1])
}
s1 = "qliksense-idps.tls"
sa = getSvcAndKey(s1)
for _, s := range sa {
t.Logf("|%s|", s)
}
if sa[0] != "qliksense-idps" || sa[1] != "tls" {
t.Fail()
t.Logf("expected service: qliksense-idps but got %s", sa[0])
t.Logf("expected key: tls but got %s", sa[1])
}
}

View File

@@ -1,73 +0,0 @@
package postflight
import (
"fmt"
"strings"
"github.com/qlik-oss/sense-installer/pkg/api"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const initContainerNameToCheck = "migration"
func (p *QliksensePostflight) DbMigrationCheck(namespace string, kubeConfigContents []byte) error {
clientset, _, err := p.CG.GetK8SClientSet(kubeConfigContents, "")
if err != nil {
err = fmt.Errorf("unable to create a kubernetes client: %v", err)
fmt.Printf("%s\n", err)
return err
}
var logsMap map[string]string
// Retrieve all deployments
p.CG.LogVerboseMessage("Retrieving logs from deployments\n")
deploymentsClient := clientset.AppsV1().Deployments(namespace)
deployments, err := deploymentsClient.List(v1.ListOptions{})
api.LogDebugMessage("Number of deployments found: %d\n", deployments.Size())
for _, deployment := range deployments.Items {
api.LogDebugMessage("Deployment name: %s\n", deployment.GetName())
if logsMap, err = p.CG.GetPodsAndPodLogsFromFailedInitContainer(clientset, deployment.Spec.Template.Labels, namespace, initContainerNameToCheck); err != nil {
fmt.Printf("%s\n", err)
return err
}
p.filterLogsForErrors(logsMap, namespace)
}
// retrieve all statefulsets
p.CG.LogVerboseMessage("Retrieving logs from statefulsets\n")
statefulsetsClient := clientset.AppsV1().StatefulSets(namespace)
statefulsets, err := statefulsetsClient.List(v1.ListOptions{})
api.LogDebugMessage("Number of statefulsets found: %d\n", statefulsets.Size())
for _, statefulset := range statefulsets.Items {
api.LogDebugMessage("Statefulset name: %s\n", statefulset.GetName())
if logsMap, err = p.CG.GetPodsAndPodLogsFromFailedInitContainer(clientset, statefulset.Spec.Template.Labels, namespace, initContainerNameToCheck); err != nil {
fmt.Printf("%s\n", err)
return err
}
p.filterLogsForErrors(logsMap, namespace)
}
return nil
}
func (p *QliksensePostflight) filterLogsForErrors(logsMap map[string]string, namespace string) {
errorLogsPresent := false
for podName, podLog := range logsMap {
containerLogs := strings.Split(podLog, "\n")
if len(containerLogs) > 0 {
for _, logLine := range containerLogs {
if strings.Contains(strings.ToLower(logLine), "error") {
errorLogsPresent = true
fmt.Printf("Logs from pod: %s\n%s\n", podName, logLine)
}
}
if errorLogsPresent {
fmt.Printf("To view more logs in this context, please run the command: kubectl logs -n %s %s %s\n", namespace, podName, initContainerNameToCheck)
}
} else {
fmt.Printf("no logs obtained\n\n")
}
}
}

View File

@@ -1,16 +0,0 @@
package postflight
import (
"github.com/qlik-oss/sense-installer/pkg/api"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
)
type PostflightOptions struct {
Verbose bool
}
type QliksensePostflight struct {
Q *qliksense.Qliksense
P *PostflightOptions
CG *api.ClientGoUtils
}

View File

@@ -1,111 +0,0 @@
package preflight
import (
"fmt"
. "github.com/logrusorgru/aurora"
ansi "github.com/mattn/go-colorable"
"github.com/pkg/errors"
)
func (qp *QliksensePreflight) RunAllPreflightChecks(kubeConfigContents []byte, namespace string, preflightOpts *PreflightOptions) error {
checkCount := 0
totalCount := 0
out := ansi.NewColorableStdout()
// Preflight minimum kuberenetes version check
if err := qp.CheckK8sVersion(namespace, kubeConfigContents); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight kubernetes minimum version check FAILED"))
fmt.Printf("Error: %v\n\n", err)
} else {
fmt.Fprintf(out, "%s\n\n", Green("Preflight kubernetes minimum version check PASSED"))
checkCount++
}
totalCount++
// Preflight deployment check
if err := qp.CheckDeployment(namespace, kubeConfigContents, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight deployment check FAILED"))
fmt.Printf("Error: %v\n\n", err)
} else {
fmt.Fprintf(out, "%s\n\n", Green("Preflight deployment check PASSED"))
checkCount++
}
totalCount++
// Preflight service check
if err := qp.CheckService(namespace, kubeConfigContents, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight service check FAILED"))
fmt.Printf("Error: %v\n\n", err)
} else {
fmt.Fprintf(out, "%s\n\n", Green("Preflight service check PASSED"))
checkCount++
}
totalCount++
// Preflight pod check
if err := qp.CheckPod(namespace, kubeConfigContents, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight pod check FAILED"))
fmt.Printf("Error: %v\n\n", err)
} else {
fmt.Fprintf(out, "%s\n\n", Green("Preflight pod check PASSED"))
checkCount++
}
totalCount++
// Preflight role check
if err := qp.CheckCreateRole(namespace, false); err != nil {
fmt.Fprintf(out, "%s\n", Red("Preflight role check FAILED"))
fmt.Printf("Error: %v\n\n", err)
} else {
fmt.Fprintf(out, "%s\n\n", Green("Preflight role check PASSED"))
checkCount++
}
totalCount++
// Preflight rolebinding check
if err := qp.CheckCreateRoleBinding(namespace, false); err != nil {
fmt.Fprintf(out, "%s\n", Red(" Preflight rolebinding check FAILED"))
fmt.Printf("Error: %v\n\n", err)
} else {
fmt.Fprintf(out, "%s\n\n", Green("Preflight rolebinding check PASSED"))
checkCount++
}
totalCount++
// Preflight serviceaccount check
if err := qp.CheckCreateServiceAccount(namespace, false); err != nil {
fmt.Fprintf(out, "%s\n", Red(" Preflight serviceaccount check FAILED"))
fmt.Printf("Error: %v\n\n", err)
} else {
fmt.Fprintf(out, "%s\n\n", Green("Preflight serviceaccount check PASSED"))
checkCount++
}
totalCount++
// Preflight mongo check
if err := qp.CheckMongo(kubeConfigContents, namespace, preflightOpts, false); err != nil {
fmt.Fprintf(out, "%s\n", Red(" Preflight mongo check FAILED"))
fmt.Printf("Error: %v\n\n", err)
} else {
fmt.Fprintf(out, "%s\n\n", Green("Preflight mongo check PASSED"))
checkCount++
}
totalCount++
// Preflight DNS check
if err := qp.CheckDns(namespace, kubeConfigContents, false); err != nil {
fmt.Fprintf(out, "%s\n", Red(" Preflight DNS check FAILED"))
fmt.Printf("Error: %v\n\n", err)
} else {
fmt.Fprintf(out, "%s\n\n", Green("Preflight DNS check PASSED"))
checkCount++
}
totalCount++
if checkCount == totalCount {
// All preflight checks were successful
return nil
}
return errors.New("1 or more preflight checks have FAILED")
}

View File

@@ -1,156 +0,0 @@
package preflight
import (
"fmt"
"k8s.io/client-go/kubernetes"
)
func (p *QliksensePreflight) CheckDeployment(namespace string, kubeConfigContents []byte, cleanup bool) error {
clientset, _, err := p.CG.GetK8SClientSet(kubeConfigContents, "")
if err != nil {
err = fmt.Errorf("Kube config error: %v\n", err)
return err
}
// Deployment check
if !cleanup {
p.CG.LogVerboseMessage("Preflight deployment check: \n")
p.CG.LogVerboseMessage("--------------------------- \n")
}
err = p.checkPfDeployment(clientset, namespace, cleanup)
if err != nil {
p.CG.LogVerboseMessage("Preflight Deployment check: FAILED\n")
return err
}
if !cleanup {
p.CG.LogVerboseMessage("Completed preflight deployment check\n")
}
return nil
}
func (p *QliksensePreflight) CheckService(namespace string, kubeConfigContents []byte, cleanup bool) error {
clientset, _, err := p.CG.GetK8SClientSet(kubeConfigContents, "")
if err != nil {
err = fmt.Errorf("unable to create a kubernetes client: %v\n", err)
return err
}
// Service check
if !cleanup {
p.CG.LogVerboseMessage("Preflight service check: \n")
p.CG.LogVerboseMessage("------------------------ \n")
}
err = p.checkPfService(clientset, namespace, cleanup)
if err != nil {
p.CG.LogVerboseMessage("Preflight Service check: FAILED\n")
return err
}
if !cleanup {
p.CG.LogVerboseMessage("Completed preflight service check\n")
}
return nil
}
func (p *QliksensePreflight) CheckPod(namespace string, kubeConfigContents []byte, cleanup bool) error {
clientset, _, err := p.CG.GetK8SClientSet(kubeConfigContents, "")
if err != nil {
err = fmt.Errorf("error: unable to create a kubernetes client: %v\n", err)
return err
}
// Pod check
if !cleanup {
p.CG.LogVerboseMessage("Preflight pod check: \n")
p.CG.LogVerboseMessage("-------------------- \n")
}
err = p.checkPfPod(clientset, namespace, cleanup)
if err != nil {
p.CG.LogVerboseMessage("Preflight Pod check: FAILED\n")
return err
}
if !cleanup {
p.CG.LogVerboseMessage("Completed preflight pod check\n")
}
return nil
}
func (p *QliksensePreflight) checkPfPod(clientset kubernetes.Interface, namespace string, cleanup bool) error {
// delete the pod we are going to create, if it already exists in the cluster
podName := "pod-pf-check"
p.CG.DeletePod(clientset, namespace, podName)
if cleanup {
return nil
}
commandToRun := []string{}
imageName, err := p.GetPreflightConfigObj().GetImageName(nginx, true)
if err != nil {
return err
}
// create a pod
pod, err := p.CG.CreatePreflightTestPod(clientset, namespace, podName, imageName, nil, commandToRun)
if err != nil {
err = fmt.Errorf("unable to create pod - %v\n", err)
return err
}
defer p.CG.DeletePod(clientset, namespace, podName)
if err := p.CG.WaitForPod(clientset, namespace, pod); err != nil {
return err
}
p.CG.LogVerboseMessage("Preflight pod creation check: PASSED\n")
p.CG.LogVerboseMessage("Cleaning up resources...\n")
return nil
}
func (p *QliksensePreflight) checkPfService(clientset kubernetes.Interface, namespace string, cleanup bool) error {
// delete the service we are going to create, if it already exists in the cluster
serviceName := "svc-pf-check"
p.CG.DeleteService(clientset, namespace, serviceName)
if cleanup {
return nil
}
// creating service
pfService, err := p.CG.CreatePreflightTestService(clientset, namespace, serviceName)
if err != nil {
err = fmt.Errorf("unable to create service - %v\n", err)
return err
}
defer p.CG.DeleteService(clientset, namespace, serviceName)
_, err = p.CG.GetService(clientset, namespace, pfService.GetName())
if err != nil {
err = fmt.Errorf("unable to retrieve service - %v\n", err)
return err
}
p.CG.LogVerboseMessage("Preflight service creation check: PASSED\n")
p.CG.LogVerboseMessage("Cleaning up resources...\n")
return nil
}
func (p *QliksensePreflight) checkPfDeployment(clientset kubernetes.Interface, namespace string, cleanup bool) error {
// delete the deployment we are going to create, if it already exists in the cluster
depName := "deployment-preflight-check"
p.CG.DeleteDeployment(clientset, namespace, depName)
if cleanup {
return nil
}
// check if we are able to create a deployment
imageName, err := p.GetPreflightConfigObj().GetImageName(nginx, true)
if err != nil {
return err
}
pfDeployment, err := p.CG.CreatePreflightTestDeployment(clientset, namespace, depName, imageName)
if err != nil {
err = fmt.Errorf("unable to create deployment - %v\n", err)
return err
}
defer p.CG.DeleteDeployment(clientset, namespace, depName)
if err := p.CG.WaitForDeployment(clientset, namespace, pfDeployment); err != nil {
return err
}
p.CG.LogVerboseMessage("Preflight Deployment check: PASSED\n")
p.CG.LogVerboseMessage("Cleaning up resources...\n")
return nil
}

View File

@@ -1,110 +0,0 @@
package preflight
import (
"fmt"
"strings"
"k8s.io/client-go/kubernetes"
)
const (
nginx = "nginx"
netcat = "netcat"
)
func (p *QliksensePreflight) CheckDns(namespace string, kubeConfigContents []byte, cleanup bool) error {
depName := "dep-dns-preflight-check"
serviceName := "svc-dns-pf-check"
podName := "pf-pod-1"
if !cleanup {
p.CG.LogVerboseMessage("Preflight DNS check: \n")
p.CG.LogVerboseMessage("------------------- \n")
}
clientset, _, err := p.CG.GetK8SClientSet(kubeConfigContents, "")
if err != nil {
err = fmt.Errorf("unable to create a kubernetes client: %v\n", err)
return err
}
// delete the deployment we are going to create, if it already exists in the cluster
p.runDNSCleanup(clientset, namespace, podName, serviceName, depName)
if cleanup {
return nil
}
// creating deployment
nginxImageName, err := p.GetPreflightConfigObj().GetImageName(nginx, true)
if err != nil {
return err
}
dnsDeployment, err := p.CG.CreatePreflightTestDeployment(clientset, namespace, depName, nginxImageName)
if err != nil {
err = fmt.Errorf("unable to create deployment: %v\n", err)
return err
}
defer p.CG.DeleteDeployment(clientset, namespace, depName)
if err := p.CG.WaitForDeployment(clientset, namespace, dnsDeployment); err != nil {
return err
}
// creating service
dnsService, err := p.CG.CreatePreflightTestService(clientset, namespace, serviceName)
if err != nil {
err = fmt.Errorf("unable to create service : %s, %s\n", serviceName, err)
return err
}
defer p.CG.DeleteService(clientset, namespace, serviceName)
// create a pod
commandToRun := []string{"sh", "-c", "sleep 10; nc -z -v -w 1 " + dnsService.Name + " 80"}
netcatImageName, err := p.GetPreflightConfigObj().GetImageName(netcat, true)
if err != nil {
err = fmt.Errorf("unable to retrieve image : %v\n", err)
return err
}
dnsPod, err := p.CG.CreatePreflightTestPod(clientset, namespace, podName, netcatImageName, nil, commandToRun)
if err != nil {
err = fmt.Errorf("unable to create pod : %s, %s\n", podName, err)
return err
}
defer p.CG.DeletePod(clientset, namespace, podName)
if err := p.CG.WaitForPod(clientset, namespace, dnsPod); err != nil {
return err
}
if len(dnsPod.Spec.Containers) == 0 {
err := fmt.Errorf("there are no containers in the pod")
return err
}
p.CG.WaitForPodToDie(clientset, namespace, dnsPod)
logStr, err := p.CG.GetPodLogs(clientset, dnsPod)
if err != nil {
err = fmt.Errorf("unable to execute dns check in the cluster: %v", err)
return err
}
if strings.HasSuffix(strings.TrimSpace(logStr), "succeeded!") {
p.CG.LogVerboseMessage("Preflight DNS check: PASSED\n")
} else {
err = fmt.Errorf("Expected response not found\n")
return err
}
if !cleanup {
p.CG.LogVerboseMessage("Completed preflight DNS check\n")
p.CG.LogVerboseMessage("Cleaning up resources...\n")
}
return nil
}
func (p *QliksensePreflight) runDNSCleanup(clientset kubernetes.Interface, namespace, podName, serviceName, depName string) {
p.CG.DeleteDeployment(clientset, namespace, depName)
p.CG.DeletePod(clientset, namespace, podName)
p.CG.DeleteService(clientset, namespace, serviceName)
}

View File

@@ -1,207 +0,0 @@
package preflight
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/Masterminds/semver/v3"
"github.com/pkg/errors"
"github.com/qlik-oss/sense-installer/pkg/api"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
apiv1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
)
const (
preflight_mongo = "preflight-mongo"
caCertMountPath = "/etc/ssl/certs/ca-certificates.crt"
)
func (qp *QliksensePreflight) CheckMongo(kubeConfigContents []byte, namespace string, preflightOpts *PreflightOptions, cleanup bool) error {
if !cleanup {
qp.CG.LogVerboseMessage("Preflight mongodb check: \n")
qp.CG.LogVerboseMessage("------------------------ \n")
}
var currentCR *qapi.QliksenseCR
var err error
qConfig := qapi.NewQConfig(qp.Q.QliksenseHome)
qConfig.SetNamespace(namespace)
currentCR, err = qConfig.GetCurrentCR()
if err != nil {
qp.CG.LogVerboseMessage("Unable to retrieve current CR: %v\n", err)
return err
}
decryptedCR, err := qConfig.GetDecryptedCr(currentCR)
if err != nil {
qp.CG.LogVerboseMessage("An error occurred while retrieving mongodbUrl from current CR: %v\n", err)
return err
}
if preflightOpts.MongoOptions.MongodbUrl == "" && !cleanup {
// infer mongoDbUrl from currentCR
qp.CG.LogVerboseMessage("mongodbUri is empty, infer from CR\n")
preflightOpts.MongoOptions.MongodbUrl = strings.TrimSpace(decryptedCR.Spec.GetFromSecrets("qliksense", "mongodbUri"))
}
if preflightOpts.MongoOptions.CaCertFile == "" && !cleanup {
caCertStr := decryptedCR.Spec.GetFromSecrets("qliksense", "caCertificates")
tmpDir := os.TempDir()
caCrtFile := filepath.Join(tmpDir, "rootCA.crt")
api.LogDebugMessage("received ca crt: %s\n", caCertStr)
if err := ioutil.WriteFile(caCrtFile, []byte(caCertStr), 0644); err != nil {
return fmt.Errorf("unable to write CA crt to file: %v", err)
}
preflightOpts.MongoOptions.CaCertFile = caCrtFile
}
if !cleanup {
qp.CG.LogVerboseMessage("MongodbUrl: %s\n", preflightOpts.MongoOptions.MongodbUrl)
// if mongodbUrl is empty, abort check
if preflightOpts.MongoOptions.MongodbUrl == "" {
qp.CG.LogVerboseMessage("Mongodb Url is empty, hence aborting preflight check\n")
return errors.New("MongodbUrl is empty")
}
}
if err := qp.mongoConnCheck(kubeConfigContents, namespace, preflightOpts, cleanup); err != nil {
return err
}
if !cleanup {
qp.CG.LogVerboseMessage("Completed preflight mongodb check\n")
}
return nil
}
func (p *QliksensePreflight) mongoConnCheck(kubeConfigContents []byte, namespace string, preflightOpts *PreflightOptions, cleanup bool) error {
caCertSecretName := "ca-certificates-crt"
mongoPodName := "pf-mongo-pod"
clientset, _, err := p.CG.GetK8SClientSet(kubeConfigContents, "")
if err != nil {
err = fmt.Errorf("unable to create a kubernetes client: %v\n", err)
return err
}
// cleanup before starting check
p.runMongoCleanup(clientset, namespace, mongoPodName, caCertSecretName)
if cleanup {
return nil
}
secrets := map[string]string{}
if preflightOpts.MongoOptions.CaCertFile != "" {
caCertSecret, err := p.createSecret(clientset, namespace, preflightOpts.MongoOptions.CaCertFile, caCertSecretName)
if err != nil {
err = fmt.Errorf("unable to create a ca cert kubernetes secret: %v\n", err)
return err
}
defer p.CG.DeleteK8sSecret(clientset, namespace, caCertSecret.Name)
secrets[caCertSecretName] = caCertMountPath
}
commandToRun := []string{"./preflight-mongo", fmt.Sprintf(`-url="%s"`, preflightOpts.MongoOptions.MongodbUrl)}
api.LogDebugMessage("Mongo command: %s\n", strings.Join(commandToRun, " "))
// create a pod
imageName, err := p.GetPreflightConfigObj().GetImageName(preflight_mongo, true)
if err != nil {
err = fmt.Errorf("unable to retrieve image : %v\n", err)
return err
}
api.LogDebugMessage("image name to be used: %s\n", imageName)
mongoPod, err := p.CG.CreatePreflightTestPod(clientset, namespace, mongoPodName, imageName, secrets, commandToRun)
if err != nil {
err = fmt.Errorf("unable to create pod : %v\n", err)
return err
}
defer p.CG.DeletePod(clientset, namespace, mongoPodName)
if err := p.CG.WaitForPod(clientset, namespace, mongoPod); err != nil {
return err
}
if len(mongoPod.Spec.Containers) == 0 {
err := fmt.Errorf("there are no containers in the pod- %v\n", err)
return err
}
p.CG.WaitForPodToDie(clientset, namespace, mongoPod)
logStr, err := p.CG.GetPodLogs(clientset, mongoPod)
if err != nil {
err = fmt.Errorf("unable to execute mongo check in the cluster: %v\n", err)
return err
}
// check mongo server version
ok, err := p.checkMongoVersion(logStr)
if !ok || err != nil {
return err
}
// check if connection succeeded
stringToCheck := "qlik - connection succeeded!!"
if strings.Contains(logStr, stringToCheck) {
p.CG.LogVerboseMessage("Preflight mongo check: PASSED\n")
} else {
err = fmt.Errorf("Connection failed: %s\n", logStr)
return err
}
return nil
}
func (p *QliksensePreflight) checkMongoVersion(logStr string) (bool, error) {
// check mongo server version
api.LogDebugMessage("Minimum required mongo version: %s\n", p.GetPreflightConfigObj().GetMinMongoVersion())
mongoVersionStrToCheck := "qlik mongo server version:"
if strings.Contains(logStr, mongoVersionStrToCheck) {
logLines := strings.Split(logStr, "\n")
for _, eachline := range logLines {
if strings.Contains(eachline, mongoVersionStrToCheck) {
mongoVersionLog := strings.Split(eachline, ":")
if len(mongoVersionLog) < 2 {
continue
}
mongoVersionStr := strings.ReplaceAll(strings.TrimSpace(mongoVersionLog[1]), `"`, "")
api.LogDebugMessage("Extracted mongo version from pod log: %s\n", mongoVersionStr)
currentMongoVersionSemver, err := semver.NewVersion(mongoVersionStr)
if err != nil {
err = fmt.Errorf("Unable to convert minimum mongo version into semver version:%v\n", err)
return false, err
}
minMongoVersionSemver, err := semver.NewVersion(p.GetPreflightConfigObj().GetMinMongoVersion())
if err != nil {
err = fmt.Errorf("Unable to convert required minimum mongo version into semver version:%v\n", err)
return false, err
}
if currentMongoVersionSemver.GreaterThan(minMongoVersionSemver) || currentMongoVersionSemver.Equal(minMongoVersionSemver) {
p.CG.LogVerboseMessage("Current mongodb server version %s is greater than or equal to minimum required mongodb version: %s\n", currentMongoVersionSemver, minMongoVersionSemver)
return true, nil
}
err = fmt.Errorf("Current mongodb server version %s is less than minimum required mongodb version: %s", currentMongoVersionSemver, minMongoVersionSemver)
return false, err
}
}
}
err := errors.New("Unable to infer mongodb server version")
return false, err
}
func (p *QliksensePreflight) createSecret(clientset kubernetes.Interface, namespace, certFile, certSecretName string) (*apiv1.Secret, error) {
certBytes, err := ioutil.ReadFile(certFile)
if err != nil {
return nil, err
}
certSecret, err := p.CG.CreatePreflightTestSecret(clientset, namespace, certSecretName, certBytes)
if err != nil {
err = fmt.Errorf("unable to create secret with cert : %v\n", err)
return nil, err
}
return certSecret, nil
}
func (p *QliksensePreflight) runMongoCleanup(clientset kubernetes.Interface, namespace, mongoPodName, caCertSecretName string) {
p.CG.DeletePod(clientset, namespace, mongoPodName)
p.CG.DeleteK8sSecret(clientset, namespace, caCertSecretName)
}

View File

@@ -1,58 +0,0 @@
package preflight
import (
"github.com/qlik-oss/sense-installer/pkg/api"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
)
type PreflightOptions struct {
Verbose bool
MongoOptions *MongoOptions
}
// // LogVerboseMessage logs a verbose message
// func (p *PreflightOptions) LogVerboseMessage(strMessage string, args ...interface{}) {
// if p.Verbose || os.Getenv("QLIKSENSE_DEBUG") == "true" {
// fmt.Printf(strMessage, args...)
// }
// }
type MongoOptions struct {
MongodbUrl string
CaCertFile string
}
type QliksensePreflight struct {
Q *qliksense.Qliksense
P *PreflightOptions
CG *api.ClientGoUtils
}
func (qp *QliksensePreflight) GetPreflightConfigObj() *api.PreflightConfig {
return api.NewPreflightConfig(qp.Q.QliksenseHome)
}
func (qp *QliksensePreflight) Cleanup(namespace string, kubeConfigContents []byte) error {
qp.CG.LogVerboseMessage("Preflight clean\n")
qp.CG.LogVerboseMessage("----------------\n")
qp.CG.LogVerboseMessage("Removing deployment...\n")
qp.CheckDeployment(namespace, kubeConfigContents, true)
qp.CG.LogVerboseMessage("Removing service...\n")
qp.CheckService(namespace, kubeConfigContents, true)
qp.CG.LogVerboseMessage("Removing pod...\n")
qp.CheckPod(namespace, kubeConfigContents, true)
qp.CG.LogVerboseMessage("Removing role...\n")
qp.CheckCreateRole(namespace, true)
qp.CG.LogVerboseMessage("Removing rolebinding...\n")
qp.CheckCreateRoleBinding(namespace, true)
qp.CG.LogVerboseMessage("Removing serviceaccount...\n")
qp.CheckCreateServiceAccount(namespace, true)
qp.CG.LogVerboseMessage("Removing DNS check components...\n")
qp.CheckDns(namespace, kubeConfigContents, true)
qp.CG.LogVerboseMessage("Removing mongo check components...\n")
qp.CheckMongo(kubeConfigContents, namespace, &PreflightOptions{MongoOptions: &MongoOptions{}}, true)
return nil
}

View File

@@ -1,174 +0,0 @@
package preflight
import (
"fmt"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/qlik-oss/sense-installer/pkg/api"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
"github.com/qlik-oss/sense-installer/pkg/qliksense"
)
func (qp *QliksensePreflight) CheckCreateRole(namespace string, cleanup bool) error {
// create a Role
if !cleanup {
qp.CG.LogVerboseMessage("Preflight role check: \n")
qp.CG.LogVerboseMessage("--------------------- \n")
}
err := qp.checkCreateEntity(namespace, "Role", cleanup)
if err != nil {
return err
}
if !cleanup {
qp.CG.LogVerboseMessage("Completed preflight role check\n")
}
return nil
}
func (qp *QliksensePreflight) CheckCreateRoleBinding(namespace string, cleanup bool) error {
// create a RoleBinding
if !cleanup {
qp.CG.LogVerboseMessage("Preflight rolebinding check: \n")
qp.CG.LogVerboseMessage("---------------------------- \n")
}
err := qp.checkCreateEntity(namespace, "RoleBinding", cleanup)
if err != nil {
return err
}
if !cleanup {
qp.CG.LogVerboseMessage("Completed preflight rolebinding check\n")
}
return nil
}
func (qp *QliksensePreflight) CheckCreateServiceAccount(namespace string, cleanup bool) error {
// create a service account
if !cleanup {
qp.CG.LogVerboseMessage("Preflight serviceaccount check: \n")
qp.CG.LogVerboseMessage("------------------------------- \n")
}
err := qp.checkCreateEntity(namespace, "ServiceAccount", cleanup)
if err != nil {
return err
}
if !cleanup {
qp.CG.LogVerboseMessage("Completed preflight serviceaccount check\n")
}
return nil
}
func (qp *QliksensePreflight) checkCreateEntity(namespace, entityToTest string, cleanup bool) error {
qConfig := qapi.NewQConfig(qp.Q.QliksenseHome)
var currentCR *qapi.QliksenseCR
mfroot := ""
kusDir := ""
resultYamlBytes := []byte("")
var err error
currentCR, err = qConfig.GetCurrentCR()
if err != nil {
qp.CG.LogVerboseMessage("Unable to retrieve current CR: %v\n", err)
return err
}
if currentCR.IsRepoExist() {
mfroot = currentCR.Spec.GetManifestsRoot()
} else if tempDownloadedDir, err := qliksense.DownloadFromGitRepoToTmpDir(qliksense.QLIK_GIT_REPO, "master"); err != nil {
qp.CG.LogVerboseMessage("Unable to Download from git repo to tmp dir: %v\n", err)
return err
} else {
mfroot = tempDownloadedDir
}
if currentCR.Spec.Profile == "" {
kusDir = filepath.Join(mfroot, "manifests", "docker-desktop")
} else {
kusDir = filepath.Join(mfroot, "manifests", currentCR.Spec.Profile)
}
if len(resultYamlBytes) == 0 {
resultYamlBytes, err = qliksense.ExecuteKustomizeBuild(kusDir)
if err != nil {
err := fmt.Errorf("Unable to retrieve manifests from executing kustomize: %s, error: %v", kusDir, err)
return err
}
}
sa := qliksense.GetYamlsFromMultiDoc(string(resultYamlBytes), entityToTest)
if sa != "" {
sa = strings.Replace(sa, "name: qliksense", "name: preflight", -1)
} else {
err := fmt.Errorf("Unable to retrieve yamls to apply on cluster from dir: %s, error: %v", kusDir, err)
return err
}
namespace = "" // namespace is handled when generating the manifests
// check if entity already exists in the cluster, if so - delete it
api.KubectlDeleteVerbose(sa, namespace, qp.P.Verbose)
if cleanup {
return nil
}
defer func() {
qp.CG.LogVerboseMessage("Cleaning up resources...\n")
err := api.KubectlDeleteVerbose(sa, namespace, qp.P.Verbose)
if err != nil {
qp.CG.LogVerboseMessage("Preflight cleanup failed!\n")
}
}()
err = api.KubectlApplyVerbose(sa, namespace, qp.P.Verbose)
if err != nil {
err := fmt.Errorf("Failed to create entity on the cluster: %v", err)
return err
}
qp.CG.LogVerboseMessage("Preflight %s check: PASSED\n", entityToTest)
return nil
}
func (qp *QliksensePreflight) CheckCreateRB(namespace string, kubeConfigContents []byte) error {
// create a role
qp.CG.LogVerboseMessage("Preflight createRole check: \n")
qp.CG.LogVerboseMessage("--------------------------- \n")
errStr := strings.Builder{}
err1 := qp.checkCreateEntity(namespace, "Role", false)
if err1 != nil {
errStr.WriteString(err1.Error())
errStr.WriteString("\n")
qp.CG.LogVerboseMessage("%v\n", err1)
qp.CG.LogVerboseMessage("Preflight role check: FAILED\n")
}
qp.CG.LogVerboseMessage("Completed preflight role check\n\n")
// create a roleBinding
qp.CG.LogVerboseMessage("Preflight rolebinding check: \n")
qp.CG.LogVerboseMessage("---------------------------- \n")
err2 := qp.checkCreateEntity(namespace, "RoleBinding", false)
if err2 != nil {
errStr.WriteString(err2.Error())
errStr.WriteString("\n")
qp.CG.LogVerboseMessage("%v\n", err2)
qp.CG.LogVerboseMessage("Preflight rolebinding check: FAILED\n")
}
qp.CG.LogVerboseMessage("Completed preflight rolebinding check\n\n")
// create a service account
qp.CG.LogVerboseMessage("Preflight serviceaccount check: \n")
qp.CG.LogVerboseMessage("------------------------------- \n")
err3 := qp.checkCreateEntity(namespace, "ServiceAccount", false)
if err3 != nil {
errStr.WriteString(err3.Error())
errStr.WriteString("\n")
qp.CG.LogVerboseMessage("%v\n", err3)
qp.CG.LogVerboseMessage("Preflight serviceaccount check: FAILED\n")
}
qp.CG.LogVerboseMessage("Completed preflight serviceaccount check\n\n")
if err1 != nil || err2 != nil || err3 != nil {
qp.CG.LogVerboseMessage("Preflight authcheck: FAILED\n")
qp.CG.LogVerboseMessage("Completed preflight authcheck\n")
return errors.New(errStr.String())
}
qp.CG.LogVerboseMessage("Preflight authcheck: PASSED\n")
qp.CG.LogVerboseMessage("Completed preflight authcheck\n")
return nil
}

View File

@@ -1,52 +0,0 @@
package preflight
import (
"fmt"
"github.com/Masterminds/semver/v3"
"github.com/qlik-oss/sense-installer/pkg/api"
"k8s.io/apimachinery/pkg/version"
)
func (p *QliksensePreflight) CheckK8sVersion(namespace string, kubeConfigContents []byte) error {
p.CG.LogVerboseMessage("Preflight kubernetes version check: \n")
p.CG.LogVerboseMessage("----------------------------------- \n")
var currentVersion *semver.Version
clientset, _, err := p.CG.GetK8SClientSet(kubeConfigContents, "")
if err != nil {
err = fmt.Errorf("Unable to create clientset: %v\n", err)
return err
}
var serverVersion *version.Info
if err := p.CG.RetryOnError(func() (err error) {
serverVersion, err = clientset.ServerVersion()
return err
}); err != nil {
err = fmt.Errorf("Unable to get server version: %v\n", err)
return err
}
p.CG.LogVerboseMessage("Kubernetes API Server version: %s\n", serverVersion.String())
// Compare K8s version on the cluster with minimum supported k8s version
currentVersion, err = semver.NewVersion(serverVersion.String())
if err != nil {
err = fmt.Errorf("Unable to convert server version into semver version: %v\n", err)
return err
}
api.LogDebugMessage("Current Kubernetes Version: %v\n", currentVersion)
minK8sVersionSemver, err := semver.NewVersion(p.GetPreflightConfigObj().GetMinK8sVersion())
if err != nil {
err = fmt.Errorf("Unable to convert minimum Kubernetes version into semver version:%v\n", err)
return err
}
if currentVersion.GreaterThan(minK8sVersionSemver) {
p.CG.LogVerboseMessage("Current Kubernetes API Server version %s is greater than or equal to minimum required version: %s\n", currentVersion, minK8sVersionSemver)
} else {
err = fmt.Errorf("Current Kubernetes API Server version %s is less than minimum required version: %s", currentVersion, minK8sVersionSemver)
return err
}
return nil
}

Binary file not shown.

View File

@@ -1,244 +0,0 @@
package qliksense
import (
"bytes"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"sort"
kapis_git "github.com/qlik-oss/k-apis/pkg/git"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
"gopkg.in/yaml.v2"
)
type patch struct {
Target struct {
Kind string `yaml:"kind"`
LabelSelector string `yaml:"labelSelector"`
} `yaml:"target"`
Patch string `yaml:"patch"`
}
type selectivePatch struct {
APIVersion string `yaml:"apiVersion"`
Metadata struct {
Name string `yaml:"name"`
} `yaml:"metadata"`
Enabled bool `yaml:"enabled"`
Patches []patch `yaml:"patches"`
}
type helmChart struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Metadata struct {
Name string `yaml:"name"`
} `yaml:"metadata"`
ReleaseNamespace string `yaml:"releaseNamespace"`
ChartHome string `yaml:"chartHome"`
ChartRepo string `yaml:"chartRepo"`
ChartName string `yaml:"chartName"`
ChartVersion string `yaml:"chartVersion"`
}
type VersionOutput struct {
QliksenseVersion string `yaml:"qlikSenseVersion"`
Images []string `yaml:"images"`
}
type nullWriter struct {
}
func (nw *nullWriter) Write(p []byte) (n int, err error) {
return len(p), nil
}
const (
defaultProfile = "docker-desktop"
defaultConfigRepoGitUrl = "https://github.com/qlik-oss/qliksense-k8s"
)
func (q *Qliksense) About(gitRef, profile string) (*VersionOutput, error) {
configDirectory, isTemporary, profile, err := q.getConfigDirectory(defaultConfigRepoGitUrl, gitRef, profile)
if err != nil {
return nil, err
} else if isTemporary {
defer os.RemoveAll(configDirectory)
}
return q.AboutDir(configDirectory, profile)
}
func (q *Qliksense) AboutDir(configDirectory, profile string) (*VersionOutput, error) {
if chartVersion, err := getChartVersion(filepath.Join(configDirectory, "transformers", "qseokversion.yaml"), "qliksense"); err != nil {
return nil, err
} else if kuzManifest, err := executeKustomizeBuildWithStdoutProgress(filepath.Join(configDirectory, "manifests", profile)); err != nil {
return nil, err
} else if images, err := getImageList(kuzManifest); err != nil {
return nil, err
} else {
return &VersionOutput{
QliksenseVersion: chartVersion,
Images: images,
}, nil
}
}
func (q *Qliksense) getConfigDirectory(gitUrl, gitRef, profileEntered string) (dir string, isTemporary bool, profile string, err error) {
profile = profileEntered
if profile == "" {
profile = defaultProfile
}
if gitRef != "" {
if dir, err = DownloadFromGitRepoToTmpDir(gitUrl, gitRef); err != nil {
return "", false, "", err
} else {
return dir, true, profile, nil
}
}
var exists bool
exists, dir, err = configExistsInCurrentDirectory(profile)
if err != nil {
return "", false, "", err
} else if exists {
return dir, false, profile, nil
}
var profileFromCurrentContext string
exists, dir, profileFromCurrentContext, err = q.configExistsInCurrentContext()
if err != nil {
return "", false, "", err
} else if exists {
if profileEntered == "" {
profile = profileFromCurrentContext
}
return dir, false, profile, nil
}
if dir, err = DownloadFromGitRepoToTmpDir(gitUrl, "master"); err != nil {
return "", false, "", err
} else {
return dir, true, profile, nil
}
}
//DownloadFromGitRepoToTmpDir download git repo to a temporary directory
func DownloadFromGitRepoToTmpDir(gitUrl, gitRef string) (string, error) {
if tmpDir, err := ioutil.TempDir("", ""); err != nil {
return "", err
} else {
downloadPath := path.Join(tmpDir, "repo")
if err := downloadFromGitRepo(gitUrl, gitRef, downloadPath); err != nil {
_ = os.RemoveAll(tmpDir)
return "", err
} else {
return downloadPath, nil
}
}
}
func downloadFromGitRepo(gitUrl, gitRef, destDir string) error {
if repo, err := kapis_git.CloneRepository(destDir, gitUrl, nil); err != nil {
return err
} else {
return kapis_git.Checkout(repo, gitRef, "", nil)
}
}
func configExistsInCurrentDirectory(profile string) (exists bool, currentDirectory string, err error) {
currentDirectory, err = os.Getwd()
if err == nil {
info, err := os.Stat(path.Join(currentDirectory, "manifests", profile))
if err == nil && info.IsDir() {
exists = true
}
}
return exists, currentDirectory, err
}
func (q *Qliksense) configExistsInCurrentContext() (exists bool, directory string, profile string, err error) {
qConfig := qapi.NewQConfig(q.QliksenseHome)
if currentCr, err := qConfig.GetCurrentCR(); err != nil {
return false, "", "", err
} else if currentCr.Spec.ManifestsRoot == "" {
return false, "", "", nil
} else {
return true, currentCr.Spec.GetManifestsRoot(), currentCr.Spec.Profile, nil
}
}
func getImageList(yamlContent []byte) ([]string, error) {
decoder := yaml.NewDecoder(bytes.NewReader(yamlContent))
var resource map[string]interface{}
imageMap := make(map[string]bool)
for {
err := decoder.Decode(&resource)
if err != nil {
if err != io.EOF {
return nil, err
}
break
}
traverseYamlDecodedMapRecursively(reflect.ValueOf(resource), []string{}, func(path []string, val interface{}) {
if len(path) >= 2 && path[len(path)-1] == "image" &&
(path[len(path)-2] == "containers" || path[len(path)-2] == "initContainers") {
if image, ok := val.(string); ok {
imageMap[image] = true
}
}
})
}
var sortedImageList []string
for image, v := range imageMap {
sortedImageList = append(sortedImageList, image)
// a warning "simplify range expression" if written like this 'for image _ :=range imageMap'
_ = v
}
sort.Strings(sortedImageList)
return sortedImageList, nil
}
func traverseYamlDecodedMapRecursively(val reflect.Value, path []string, visitorFunc func(path []string, val interface{})) {
kind := val.Kind()
switch kind {
case reflect.Interface:
traverseYamlDecodedMapRecursively(val.Elem(), path, visitorFunc)
case reflect.Slice:
for i := 0; i < val.Len(); i++ {
traverseYamlDecodedMapRecursively(val.Index(i), path, visitorFunc)
}
case reflect.Map:
for _, key := range val.MapKeys() {
traverseYamlDecodedMapRecursively(val.MapIndex(key), append(path, key.Interface().(string)), visitorFunc)
}
default:
if kind != reflect.Invalid {
visitorFunc(path, val.Interface())
}
}
}
func getChartVersion(versionFile, chartName string) (string, error) {
var patchInst patch
var selPatch selectivePatch
var chart helmChart
if bytes, err := ioutil.ReadFile(versionFile); err != nil {
return "", err
} else if err = yaml.Unmarshal(bytes, &selPatch); err != nil {
return "", err
}
for _, patchInst = range selPatch.Patches {
if err := yaml.Unmarshal([]byte(patchInst.Patch), &chart); err == nil {
if chart.ChartName == chartName {
return chart.ChartVersion, nil
}
}
}
return "", nil
}

View File

@@ -1,588 +0,0 @@
package qliksense
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"testing"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
)
func Test_About_getImageList(t *testing.T) {
var testCases = []struct {
name string
k8sYaml string
expectedImages []string
}{
{
name: "base",
k8sYaml: `
apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
name: nginx-deployment-1
spec:
selector:
matchLabels:
app: nginx
replicas: 2 # tells deployment to run 2 pods matching the template
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.7.9
ports:
- containerPort: 80
---
apiVersion: v1
kind: Secret
metadata:
creationTimestamp: 2018-11-15T20:46:46Z
name: mysecret
namespace: default
resourceVersion: "7579"
uid: 91460ecb-e917-11e8-98f2-025000000001
type: Opaque
data:
username: YWRtaW5pc3RyYXRvcg==
---
apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
name: nginx-deployment-2
spec:
selector:
matchLabels:
app: nginx
replicas: 2 # tells deployment to run 2 pods matching the template
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.7.9
ports:
- containerPort: 80
apiVersion: v1
kind: Service
metadata:
name: nginx
labels:
app: nginx
spec:
ports:
- port: 80
name: web
clusterIP: None
selector:
app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
selector:
matchLabels:
app: nginx # has to match .spec.template.metadata.labels
serviceName: "nginx"
replicas: 3 # by default is 1
template:
metadata:
labels:
app: nginx # has to match .spec.selector.matchLabels
spec:
terminationGracePeriodSeconds: 10
containers:
- name: nginx
image: k8s.gcr.io/nginx-slim:0.8
ports:
- containerPort: 80
name: web
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: "my-storage-class"
resources:
requests:
storage: 1Gi
---
apiVersion: batch/v1
kind: Job
metadata:
name: pi
spec:
template:
spec:
containers:
- name: pi
image: perl
command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
restartPolicy: Never
backoffLimit: 4
---
apiVersion: v1
kind: Pod
metadata:
name: init-demo
spec:
containers:
- name: nginx
image: nginx
env:
- name: FOO
value: null
ports:
- containerPort: 80
volumeMounts:
- name: workdir
mountPath: /usr/share/nginx/html
# These containers are run during pod initialization
initContainers:
- name: install
image: busybox
command:
- wget
- "-O"
- "/work-dir/index.html"
- http://kubernetes.io
volumeMounts:
- name: workdir
mountPath: "/work-dir"
dnsPolicy: Default
volumes:
- name: workdir
emptyDir: {}
`,
expectedImages: []string{"busybox", "k8s.gcr.io/nginx-slim:0.8", "nginx", "nginx:1.7.9", "perl"},
},
{
name: "works for custom resources and CronJobs",
k8sYaml: `
apiVersion: "qixmanager.qlik.com/v1"
kind: "Engine"
metadata:
name: release-name-engine-reload
spec:
metadata:
labels:
qix-engine: qix-engine
annotations:
prometheus.io/scrape: "true"
workloadType: "reload"
podSpec:
imagePullSecrets:
- name: artifactory-docker-secret
dnsConfig:
options:
- name: timeout
value: "1"
- name: single-request-reopen
containers:
- name: engine-reload
image: another-engine
---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox2
args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: OnFailure
`,
expectedImages: []string{"another-engine", "busybox2"},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
images, err := getImageList([]byte(testCase.k8sYaml))
if err != nil {
t.Fatalf("unexpected error: %v\n", err)
}
if !reflect.DeepEqual(images, testCase.expectedImages) {
t.Fatalf("expected %v, but got: %v\n", testCase.expectedImages, images)
}
})
}
}
func Test_About_getConfigDirectory(t *testing.T) {
verifyAsdBranch := func(configDir string) (ok bool, reason string) {
tmpDir := os.TempDir()
configParentDir := filepath.Dir(configDir)
if (filepath.Clean(filepath.Dir(configParentDir)) != filepath.Clean(tmpDir)) || (filepath.Base(configDir) != "repo") {
return false, fmt.Sprintf("expected config directory path: %v to be under: %v and terminate with repo", configDir, tmpDir)
}
if info, err := os.Stat(filepath.Join(configDir, "asdczxc")); err != nil || !info.Mode().IsRegular() {
return false, fmt.Sprintf(`expected to find file: "asdczxc" under directory: %v`, configDir)
}
return true, ""
}
verifyMasterBranch := func(configDir string) (ok bool, reason string) {
tmpDir := os.TempDir()
configParentDir := filepath.Dir(configDir)
if (filepath.Clean(filepath.Dir(configParentDir)) != filepath.Clean(tmpDir)) || (filepath.Base(configDir) != "repo") {
return false, fmt.Sprintf("expected config directory path: %v to be under: %v and terminate with repo", configDir, tmpDir)
}
if _, err := os.Stat(filepath.Join(configDir, "asdczxc")); err == nil || !os.IsNotExist(err) {
return false, fmt.Sprintf(`expected to NOT find file: "asdczxc"" under directory: %v`, configDir)
}
if info, err := os.Stat(filepath.Join(configDir, "sad")); err != nil || !info.Mode().IsRegular() {
return false, fmt.Sprintf(`expected to find file: "sad"" under directory: %v`, configDir)
}
return true, ""
}
var testCases = []struct {
name string
setup func(t *testing.T) (q *Qliksense, gitUrl, gitRef, profileEntered string)
verify func(q *Qliksense, configDir string, isTemporary bool, profile string) (ok bool, reason string, err error)
cleanup func(q *Qliksense, configDir string) error
}{
{
name: "config in current directory and default profile",
setup: func(t *testing.T) (q *Qliksense, gitUrl, gitRef, profileEntered string) {
currentDirectory, err := os.Getwd()
if err != nil {
t.Fatalf("error obtaining current directory: %v\n", err)
}
defaultProfilePath := path.Join(currentDirectory, "manifests", "docker-desktop")
err = os.MkdirAll(defaultProfilePath, os.ModePerm)
if err != nil {
t.Fatalf("error making path: %v, err: %v\n", defaultProfilePath, err)
}
return &Qliksense{}, "no-clone-for-you", "", ""
},
verify: func(_ *Qliksense, configDir string, isTemporary bool, profile string) (ok bool, reason string, err error) {
currentDirectory, err := os.Getwd()
if err != nil {
return false, "", err
}
if configDir != currentDirectory {
return false, fmt.Sprintf("expected config directory: %v to equal current directory: %v", configDir, currentDirectory), nil
}
if isTemporary {
return false, "expected isTemporary to be false", nil
}
if profile != "docker-desktop" {
return false, fmt.Sprintf("expected profile to be: docker-desktop, but it was: %v", profile), nil
}
return true, "", nil
},
cleanup: func(_ *Qliksense, configDir string) error {
if currentDirectory, err := os.Getwd(); err != nil {
return err
} else if err := os.RemoveAll(filepath.Join(currentDirectory, "manifests")); err != nil {
return err
}
return nil
},
},
{
name: "config in current directory and profile specified",
setup: func(t *testing.T) (q *Qliksense, gitUrl, gitRef, profileEntered string) {
currentDirectory, err := os.Getwd()
if err != nil {
t.Fatalf("error obtaining current directory: %v\n", err)
}
profileEntered = "foo"
defaultProfilePath := filepath.Join(currentDirectory, "manifests", profileEntered)
err = os.MkdirAll(defaultProfilePath, os.ModePerm)
if err != nil {
t.Fatalf("error making path: %v, err: %v\n", defaultProfilePath, err)
}
return &Qliksense{}, "no-clone-for-you", "", profileEntered
},
verify: func(_ *Qliksense, configDir string, isTemporary bool, profile string) (ok bool, reason string, err error) {
currentDirectory, err := os.Getwd()
if err != nil {
return false, "", err
}
if configDir != currentDirectory {
return false, fmt.Sprintf("expected config directory: %v to equal current directory: %v", configDir, currentDirectory), nil
}
if isTemporary {
return false, "expected isTemporary to be false", nil
}
if profile != "foo" {
return false, fmt.Sprintf("expected profile to be: foo, but it was: %v", profile), nil
}
return true, "", nil
},
cleanup: func(_ *Qliksense, configDir string) error {
if currentDirectory, err := os.Getwd(); err != nil {
return err
} else if err := os.RemoveAll(filepath.Join(currentDirectory, "manifests")); err != nil {
return err
}
return nil
},
},
{
name: "config downloaded from git based on specific git ref and default profile used",
setup: func(t *testing.T) (q *Qliksense, gitUrl, gitRef, profileEntered string) {
return &Qliksense{}, "https://github.com/test/HelloWorld", "asd", ""
},
verify: func(_ *Qliksense, configDir string, isTemporary bool, profile string) (ok bool, reason string, err error) {
ok, reason = verifyAsdBranch(configDir)
if !ok {
return ok, reason, nil
}
if !isTemporary {
return false, "expected isTemporary to be true", nil
}
if profile != "docker-desktop" {
return false, fmt.Sprintf("expected profile to be: docker-desktop, but it was: %v", profile), nil
}
return true, "", nil
},
cleanup: func(_ *Qliksense, configDir string) error {
tmpDir := os.TempDir()
tmpTmpDir := filepath.Dir(configDir)
if filepath.Clean(filepath.Dir(tmpTmpDir)) == filepath.Clean(tmpDir) && filepath.Base(configDir) == "repo" {
if err := os.RemoveAll(tmpTmpDir); err != nil {
return err
}
}
return nil
},
},
{
name: "config downloaded from git based on specific git ref and profile specified",
setup: func(t *testing.T) (q *Qliksense, gitUrl, gitRef, profileEntered string) {
return &Qliksense{}, "https://github.com/test/HelloWorld", "asd", "foo"
},
verify: func(_ *Qliksense, configDir string, isTemporary bool, profile string) (ok bool, reason string, err error) {
ok, reason = verifyAsdBranch(configDir)
if !ok {
return ok, reason, nil
}
if !isTemporary {
return false, "expected isTemporary to be true", nil
}
if profile != "foo" {
return false, fmt.Sprintf("expected profile to be: foo, but it was: %v", profile), nil
}
return true, "", nil
},
cleanup: func(_ *Qliksense, configDir string) error {
tmpDir := os.TempDir()
tmpTmpDir := filepath.Dir(configDir)
if filepath.Clean(filepath.Dir(tmpTmpDir)) == filepath.Clean(tmpDir) && filepath.Base(configDir) == "repo" {
if err := os.RemoveAll(tmpTmpDir); err != nil {
return err
}
}
return nil
},
},
{
name: "config downloaded from git from master branch and default profile used",
setup: func(t *testing.T) (q *Qliksense, gitUrl, gitRef, profileEntered string) {
if qliksenseHome, err := ioutil.TempDir("", ""); err != nil {
t.Fatalf("error creating tmp qliksenseHome directory: %v\n", err)
return nil, "", "", ""
} else {
q := &Qliksense{QliksenseHome: qliksenseHome}
if err := q.SetUpQliksenseDefaultContext(); err != nil {
t.Fatalf("error setting up default context in the tmp dir: %v\n", err)
return nil, "", "", ""
} else {
return q, "https://github.com/test/HelloWorld", "", ""
}
}
},
verify: func(_ *Qliksense, configDir string, isTemporary bool, profile string) (ok bool, reason string, err error) {
ok, reason = verifyMasterBranch(configDir)
if !ok {
return ok, reason, nil
}
if !isTemporary {
return false, "expected isTemporary to be true", nil
}
if profile != "docker-desktop" {
return false, fmt.Sprintf("expected profile to be: docker-desktop, but it was: %v", profile), nil
}
return true, "", nil
},
cleanup: func(q *Qliksense, configDir string) error {
tmpDir := os.TempDir()
tmpTmpDir := filepath.Dir(configDir)
if filepath.Clean(filepath.Dir(tmpTmpDir)) == filepath.Clean(tmpDir) && filepath.Base(configDir) == "repo" {
if err := os.RemoveAll(tmpTmpDir); err != nil {
return err
}
}
if err := os.RemoveAll(q.QliksenseHome); err != nil {
return err
}
return nil
},
},
{
name: "config downloaded from git from master branch and profile specified",
setup: func(t *testing.T) (q *Qliksense, gitUrl, gitRef, profileEntered string) {
if qliksenseHome, err := ioutil.TempDir("", ""); err != nil {
t.Fatalf("error creating tmp qliksenseHome directory: %v\n", err)
return nil, "", "", ""
} else {
q := &Qliksense{QliksenseHome: qliksenseHome}
if err := q.SetUpQliksenseDefaultContext(); err != nil {
t.Fatalf("error setting up default context in the tmp dir: %v\n", err)
return nil, "", "", ""
} else {
return q, "https://github.com/test/HelloWorld", "", "foo"
}
}
},
verify: func(_ *Qliksense, configDir string, isTemporary bool, profile string) (ok bool, reason string, err error) {
ok, reason = verifyMasterBranch(configDir)
if !ok {
return ok, reason, nil
}
if !isTemporary {
return false, "expected isTemporary to be true", nil
}
if profile != "foo" {
return false, fmt.Sprintf("expected profile to be: foo, but it was: %v", profile), nil
}
return true, "", nil
},
cleanup: func(q *Qliksense, configDir string) error {
tmpDir := os.TempDir()
tmpTmpDir := filepath.Dir(configDir)
if filepath.Clean(filepath.Dir(tmpTmpDir)) == filepath.Clean(tmpDir) && filepath.Base(configDir) == "repo" {
if err := os.RemoveAll(tmpTmpDir); err != nil {
return err
}
}
if err := os.RemoveAll(q.QliksenseHome); err != nil {
return err
}
return nil
},
},
{
name: "config loaded from current context",
setup: func(t *testing.T) (q *Qliksense, gitUrl, gitRef, profileEntered string) {
if qliksenseHome, err := ioutil.TempDir("", ""); err != nil {
t.Fatalf("error creating tmp qliksenseHome directory: %v\n", err)
return nil, "", "", ""
} else {
q := &Qliksense{QliksenseHome: qliksenseHome}
if err := q.SetUpQliksenseDefaultContext(); err != nil {
t.Fatalf("error setting up default context in the tmp dir: %v\n", err)
return nil, "", "", ""
} else if qConfig, err := qapi.NewQConfigE(q.QliksenseHome); err != nil {
t.Fatalf("cannot initiallize qConfig: %v\n", err)
return nil, "", "", ""
} else if !qConfig.IsRepoExistForCurrent("master") {
if err := q.FetchQK8s("master"); err != nil {
t.Fatalf("error fetching master config to the tmp dir: %v\n", err)
return nil, "", "", ""
}
}
return q, "no-git-clone-for-you", "", ""
}
},
verify: func(q *Qliksense, configDir string, isTemporary bool, profile string) (ok bool, reason string, err error) {
qConfig := qapi.NewQConfig(q.QliksenseHome)
expectedConfigDir := qConfig.BuildRepoPath("master")
if configDir != expectedConfigDir {
return false, fmt.Sprintf("expected configDir to be %v", expectedConfigDir), nil
}
if isTemporary {
return false, "expected isTemporary to be false", nil
}
if profile != "docker-desktop" {
return false, fmt.Sprintf("expected profile to be: docker-desktop, but it was: %v", profile), nil
}
return true, "", nil
},
cleanup: func(q *Qliksense, configDir string) error {
if err := os.RemoveAll(q.QliksenseHome); err != nil {
return err
}
return nil
},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
q, gitUrl, gitRef, profileEntered := testCase.setup(t)
configDirectory, isTemporary, profile, err := q.getConfigDirectory(gitUrl, gitRef, profileEntered)
if err != nil {
t.Fatalf("unexpected error: %v\n", err)
}
if ok, reason, err := testCase.verify(q, configDirectory, isTemporary, profile); err != nil {
t.Fatalf("unexpected verification error: %v\n", err)
} else if !ok {
t.Fatalf("verification failed: %v\n", reason)
} else if err := testCase.cleanup(q, configDirectory); err != nil {
t.Fatalf("unexpected cleanup error: %v\n", err)
}
})
}
}

View File

@@ -1,61 +0,0 @@
package qliksense
import (
"fmt"
"io"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
)
func (q *Qliksense) ApplyCRFromReader(r io.Reader, opts *InstallCommandOptions, keepPatchFiles, overwriteExistingContext, pull, push bool) error {
if err := q.LoadCr(r, overwriteExistingContext); err != nil {
return err
}
qConfig := qapi.NewQConfig(q.QliksenseHome)
cr, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
version := cr.GetLabelFromCr("version")
if pull {
fmt.Println("Pulling images...")
if err := q.PullImages(version, ""); err != nil {
return err
}
}
if push {
fmt.Println("Pushing images...")
if err := q.PushImagesForCurrentCR(); err != nil {
return err
}
}
if IsQliksenseInstalled(cr.GetName()) {
// it is needed in case want to upgrade from one version to another
if cr.Spec.ManifestsRoot == "" && cr.Spec.Git == nil {
if !qConfig.IsRepoExistForCurrent(version) {
if err := q.FetchQK8s(version); err != nil {
return err
}
}
}
return q.UpgradeQK8s(keepPatchFiles)
}
return q.InstallQK8s(version, opts, keepPatchFiles)
}
func IsQliksenseInstalled(crName string) bool {
args := []string{
"get",
"qliksense",
crName,
"-ogo-template",
`--template='{{ .metadata.name}}'`,
}
_, err := qapi.KubectlDirectOps(args, "")
if err != nil {
return false
}
return true
}

View File

@@ -1,223 +0,0 @@
package qliksense
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"github.com/mitchellh/go-homedir"
"github.com/qlik-oss/k-apis/pkg/cr"
"github.com/qlik-oss/sense-installer/pkg/api"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
)
const (
Q_INIT_CRD_PATH = "manifests/base/crds"
agreementTempalte = `
Please read the agreement at https://www.qlik.com/us/legal/license-terms
Accept the end user license agreement by providing acceptEULA=yes
`
)
func (q *Qliksense) ConfigApplyQK8s() error {
//get the current context cr
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
fmt.Println("cannot get the current-context cr", err)
return err
}
// check if acceptEULA is yes or not
if !qcr.IsEULA() {
return errors.New(agreementTempalte + "\nPlease do $ qliksense config set-configs qliksense.acceptEULA=yes\n")
}
// create patch dependent resources
fmt.Println("Installing resources used by the kuztomize patch")
if err := q.createK8sResourceBeforePatch(qcr); err != nil {
return err
}
if qcr.Spec.Git.Repository != "" {
// fetching and applying manifest will be in the operator controller
if dcr, err := qConfig.GetDecryptedCr(qcr); err != nil {
return err
} else {
return q.applyCR(dcr)
}
}
if dcr, err := qConfig.GetDecryptedCr(qcr); err != nil {
return err
} else {
return q.applyConfigToK8s(dcr)
}
}
func (q *Qliksense) configEjson() error {
qConfig := qapi.NewQConfig(q.QliksenseHome)
if ejsonKeyDir, err := qConfig.GetCurrentContextEjsonKeyDir(); err != nil {
return err
} else if err := os.Unsetenv("EJSON_KEY"); err != nil {
return err
} else if err := os.Setenv("EJSON_KEYDIR", ejsonKeyDir); err != nil {
return err
}
return nil
}
func (q *Qliksense) applyConfigToK8s(qcr *qapi.QliksenseCR) error {
if qcr.Spec.RotateKeys != "None" {
if err := q.configEjson(); err != nil {
return err
}
}
userHomeDir, err := homedir.Dir()
if err != nil {
fmt.Printf(`error fetching user's home directory: %v\n`, err)
return err
}
fmt.Println("Manifests root: " + qcr.Spec.GetManifestsRoot())
qcr.SetNamespace(qapi.GetKubectlNamespace())
// generate patches
cr.GeneratePatches(&qcr.KApiCr, path.Join(userHomeDir, ".kube", "config"))
// apply generated manifests
profilePath := filepath.Join(qcr.Spec.GetManifestsRoot(), qcr.Spec.GetProfileDir())
fmt.Printf("Generating manifests for profile: %v\n", profilePath)
mByte, err := ExecuteKustomizeBuild(profilePath)
if err != nil {
fmt.Printf("error generating manifests: %v\n", err)
return err
}
fmt.Println("Applying manifests to the cluster")
if err = qapi.KubectlApply(string(mByte), qcr.GetNamespace()); err != nil {
return err
}
return nil
}
func (q *Qliksense) ConfigViewCR() error {
//get the current context cr
r, err := q.getCurrentCRString()
if err != nil {
return err
}
oth, err := q.getCurrentCrDependentResourceAsString()
if err != nil {
return err
}
fmt.Println(r + "\n" + oth)
return nil
}
func (q *Qliksense) getCurrentCRString() (string, error) {
qConfig := qapi.NewQConfig(q.QliksenseHome)
return q.getCRString(qConfig.Spec.CurrentContext)
}
func (q *Qliksense) getCRString(contextName string) (string, error) {
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCR(contextName)
if err != nil {
fmt.Println("cannot get the context cr", err)
return "", err
}
out, err := qapi.K8sToYaml(qcr)
if err != nil {
fmt.Println("cannot unmarshal cr ", err)
return "", err
}
return string(out), nil
}
func (q *Qliksense) getCurrentCrDependentResourceAsString() (string, error) {
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCR(qConfig.Spec.CurrentContext)
if err != nil {
fmt.Println("cannot get the context cr", err)
return "", err
}
var crString strings.Builder
for svcName, v := range qcr.Spec.Secrets {
hasFile := false
for _, item := range v {
if item.ValueFrom != nil && item.ValueFrom.SecretKeyRef != nil {
hasFile = true
break
}
}
if hasFile {
secretFilePath := filepath.Join(q.QliksenseHome, QliksenseContextsDir, qcr.GetName(), QliksenseSecretsDir, svcName+".yaml")
if api.FileExists(secretFilePath) {
secretFile, err := ioutil.ReadFile(secretFilePath)
if err != nil {
return "", err
}
crString.WriteString("\n---\n")
crString.Write(secretFile)
}
}
}
crString.WriteString("\n---\n")
return crString.String(), nil
}
func (q *Qliksense) EditCR(contextName string) error {
qConfig := qapi.NewQConfig(q.QliksenseHome)
if contextName == "" {
cr, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
contextName = cr.GetName()
}
crFilePath := qConfig.GetCRFilePath(contextName)
tempFile, err := ioutil.TempFile("", "*.yaml")
if err != nil {
return err
}
crContent, err := ioutil.ReadFile(crFilePath)
if err != nil {
return err
}
if err := ioutil.WriteFile(tempFile.Name(), crContent, os.ModePerm); err != nil {
return nil
}
cmd := exec.Command(getKubeEditorTool(), tempFile.Name())
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
err = cmd.Run()
if err != nil {
return err
}
newCr, err := qapi.GetCRObject(tempFile.Name())
if err != nil {
return errors.New("cannot save the cr. Someting wrong in the file format. It is not saved\n" + err.Error())
}
oldCr, err := qapi.GetCRObject(crFilePath)
if oldCr.GetName() != newCr.GetName() {
return errors.New("cr name cannot be chagned")
}
if newCr.Validate() {
return qConfig.WriteCR(newCr)
}
return nil
}
func getKubeEditorTool() string {
editor := os.Getenv("KUBE_EDITOR")
if editor == "" {
editor = "vim"
}
return editor
}

View File

@@ -1,24 +0,0 @@
package qliksense
import (
"fmt"
"log"
"strings"
)
func AskForConfirmation(s string) bool {
for {
fmt.Printf("%s [y/n]: ", s)
var response string
_, err := fmt.Scanln(&response)
if err != nil {
log.Fatal(err)
}
if strings.EqualFold(response, "y") || strings.EqualFold(response, "yes") {
return true
} else if strings.EqualFold(response, "n") || strings.EqualFold(response, "no") {
return false
}
}
}

View File

@@ -1,643 +0,0 @@
package qliksense
import (
"errors"
"fmt"
"io"
"github.com/qlik-oss/k-apis/pkg/config"
"github.com/robfig/cron/v3"
"io/ioutil"
"log"
"os"
"path/filepath"
"reflect"
"strings"
"text/tabwriter"
b64 "encoding/base64"
. "github.com/logrusorgru/aurora"
ansi "github.com/mattn/go-colorable"
"github.com/qlik-oss/sense-installer/pkg/api"
_ "gopkg.in/yaml.v2"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
// Below are some constants to support qliksense context setup
QliksenseConfigFile = "config.yaml"
QliksenseContextsDir = "contexts"
DefaultQliksenseContext = "qlik-default"
MaxContextNameLength = 17
QliksenseSecretsDir = "secrets"
imageRegistryConfigKey = "imageRegistry"
pullSecretName = "artifactory-docker-secret"
qliksenseOperatorImageRepo = "qlik-docker-oss.bintray.io"
qliksenseOperatorImageName = "qliksense-operator"
)
func (q *Qliksense) SetSecretsFromReader(arg string, reader io.Reader, createSecret, base64Encoded bool) error {
//take only name from the arguments, value should be from reader
argName := strings.SplitN(arg, "=", 1)
if len(argName) != 1 {
return errors.New("can only have one argument from pipe")
}
valueBytes, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
return q.SetSecrets([]string{argName[0] + "=" + string(valueBytes)}, createSecret, base64Encoded)
}
// SetSecrets - set-secrets <key>=<value> commands
func (q *Qliksense) SetSecrets(args []string, isSecretSet bool, base64Encoded bool) error {
qConfig := api.NewQConfig(q.QliksenseHome)
qliksenseCR, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
// Metadata name in qliksense CR is the name of the current context
api.LogDebugMessage("Current context: %s\n", qliksenseCR.GetName())
encryptionKey, err := qConfig.GetEncryptionKeyForCurrent()
if err != nil {
return err
}
resultArgs, err := api.ProcessConfigArgs(args, base64Encoded)
if err != nil {
return err
}
for _, ra := range resultArgs {
api.LogDebugMessage("value args to be encrypted: %s\n", ra.Value)
if err := q.processSecret(ra, encryptionKey, qliksenseCR, isSecretSet); err != nil {
return err
}
}
// write modified content into context-yaml
return qConfig.WriteCR(qliksenseCR)
}
func (q *Qliksense) processSecret(ra *api.ServiceKeyValue, encryptionKey string, qliksenseCR *api.QliksenseCR, isSecretSet bool) error {
cipherText, e2 := api.EncryptData([]byte(ra.Value), encryptionKey)
if e2 != nil {
return e2
}
secretName := ""
if isSecretSet {
secretFolder := qliksenseCR.GetK8sSecretsFolder(q.QliksenseHome)
secretFileName := filepath.Join(secretFolder, ra.SvcName+".yaml")
secretName = fmt.Sprintf("%s-%s-%s", qliksenseCR.GetName(), ra.SvcName, "senseinstaller")
api.LogDebugMessage("Constructed secret name: %s", secretName)
k8sSecret := v1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
},
Type: v1.SecretTypeOpaque,
}
if !api.DirExists(secretFolder) {
if err := os.MkdirAll(secretFolder, os.ModePerm); err != nil {
err = fmt.Errorf("Not able to create %s dir: %v", secretFolder, err)
log.Println(err)
return err
}
}
// if read from file errors out, we can ignore it here
_ = api.ReadFromFile(&k8sSecret, secretFileName)
if k8sSecret.Data == nil {
k8sSecret.Data = map[string][]byte{}
}
// v1.Secret does enconding, so no need to encode again
k8sSecret.Data[ra.Key] = []byte(cipherText)
// Write secret to file
k8sSecretBytes, err := api.K8sSecretToYaml(k8sSecret)
if err != nil {
api.LogDebugMessage("Error while converting K8s secret to yaml")
return err
}
if err = ioutil.WriteFile(secretFileName, k8sSecretBytes, os.ModePerm); err != nil {
api.LogDebugMessage("Error while writing K8s secret to file")
return err
}
api.LogDebugMessage("Created a Kubernetes secret")
}
base64EncodedSecret := b64.StdEncoding.EncodeToString([]byte(cipherText))
// write into CR the keyref of the secret
qliksenseCR.Spec.AddToSecrets(ra.SvcName, ra.Key, base64EncodedSecret, secretName)
return nil
}
func (q *Qliksense) SetConfigFromReader(arg string, reader io.Reader, base64Encoded bool) error {
//take only name from the arguments, value should be from reader
argName := strings.SplitN(arg, "=", 1)
if len(argName) != 1 {
return errors.New("can only have one argument from pipe")
}
valueBytes, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
return q.SetConfigs([]string{argName[0] + "=" + string(valueBytes)}, base64Encoded)
}
// SetConfigs - set-configs <key>=<value> commands
func (q *Qliksense) SetConfigs(args []string, base64Encoded bool) error {
// retieve current context from config.yaml
qConfig := api.NewQConfig(q.QliksenseHome)
qliksenseCR, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
resultArgs, err := api.ProcessConfigArgs(args, base64Encoded)
if err != nil {
return err
}
for _, ra := range resultArgs {
qliksenseCR.Spec.AddToConfigs(ra.SvcName, ra.Key, ra.Value)
}
// write modified content into context.yaml
return qConfig.WriteCR(qliksenseCR)
}
func caseInsenstiveFieldByName(v reflect.Value, name string) reflect.Value {
name = strings.ToLower(name)
return v.FieldByNameFunc(func(n string) bool { return strings.ToLower(n) == name })
}
func validateCR(key string, keySub string, value string, crSpec *api.QliksenseCR) (bool, *api.QliksenseCR) {
cr := reflect.ValueOf(crSpec.Spec)
keyValid := caseInsenstiveFieldByName(reflect.Indirect(cr), key)
if !keyValid.IsValid() {
//not in main spec
fmt.Println(key, "is an invalid key")
return false, crSpec
} else if keySub == "" {
if key == "rotatekeys" {
if _, err := validateInput(value); err != nil {
return false, crSpec
}
}
}
// checks if it is git or gitops
if keySub != "" {
if !keyValid.IsNil() {
if !caseInsenstiveFieldByName(reflect.Indirect(keyValid), keySub).IsValid() {
fmt.Println(keySub, "is an invalid key")
return false, crSpec
} else {
// verify gitops enabled and gitops schedule
switch keySub {
case "schedule":
if _, err := cron.ParseStandard(value); err != nil {
fmt.Println("Please enter string with standard cron scheduling syntax ")
return false, crSpec
}
case "enabled":
if !strings.EqualFold(value, "yes") && !strings.EqualFold(value, "no") {
fmt.Println("Please use yes or no for key enabled")
return false, crSpec
}
}
}
} else {
switch key {
case "opsrunner":
crSpec.Spec.OpsRunner = &config.OpsRunner{}
case "git":
crSpec.Spec.Git = &config.Repo{}
}
}
}
return true, crSpec
}
// SetOtherConfigs - set profile/storageclassname/git.repository/manifestRoot commands
func (q *Qliksense) SetOtherConfigs(args []string) error {
// retieve current context from config.yaml
qConfig := api.NewQConfig(q.QliksenseHome)
qliksenseCR, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
// modify appropriate fields
if len(args) == 0 {
err := fmt.Errorf("No args were provided. Please provide args to configure the current context")
log.Println(err)
return err
}
for _, arg := range args {
if strings.HasPrefix(arg, "fetchSource.") {
if err := q.processSetFetchSource(arg, qliksenseCR); err != nil {
return err
}
} else if strings.HasPrefix(arg, "git.") {
if err := q.processSetGit(arg, qliksenseCR); err != nil {
return err
}
} else if strings.HasPrefix(arg, "opsRunner.") {
if err := q.processSetOpsRunner(arg, qliksenseCR); err != nil {
return err
}
} else {
if err := processSetSingleArg(arg, qliksenseCR); err != nil {
return err
}
}
fmt.Println(Green("Successfully added to Custom Resource Spec"))
}
// write modified content into context.yaml
return qConfig.WriteCR(qliksenseCR)
}
func processSetSingleArg(arg string, cr *api.QliksenseCR) error {
nv := strings.Split(arg, "=")
switch nv[0] {
case "manifestsRoot":
cr.Spec.ManifestsRoot = nv[1]
case "profile":
cr.Spec.Profile = nv[1]
case "storageClassName":
cr.Spec.StorageClassName = nv[1]
case "rotateKeys":
valid := false
for _, v := range []string{"yes", "no", "None"} {
if nv[1] == v {
valid = true
}
}
if !valid {
return errors.New("please povide rotateKeys=yes|no|None")
}
cr.Spec.RotateKeys = nv[1]
default:
return errors.New("Please enter one of: profile, storageClassName,rotateKeys, manifestRoot to configure the current context")
}
return nil
}
func (q *Qliksense) processSetFetchSource(arg string, cr *api.QliksenseCR) error {
args := strings.Split(arg, "=")
subs := strings.Split(args[0], ".")
if cr.Spec.FetchSource == nil {
cr.Spec.FetchSource = &config.Repo{}
}
switch subs[1] {
case "repository":
cr.Spec.FetchSource.Repository = args[1]
case "accessToken":
qConfig := api.NewQConfig(q.QliksenseHome)
key, err := qConfig.GetEncryptionKeyFor(cr.GetName())
if err != nil {
return err
}
return cr.SetFetchAccessToken(args[1], key)
case "secretName":
cr.Spec.FetchSource.SecretName = args[1]
case "userName":
cr.Spec.FetchSource.UserName = args[1]
default:
return errors.New(arg + " does not match any cr spec")
}
return nil
}
func (q *Qliksense) processSetGit(arg string, cr *api.QliksenseCR) error {
args := strings.Split(arg, "=")
subs := strings.Split(args[0], ".")
if cr.Spec.Git == nil {
cr.Spec.Git = &config.Repo{}
}
switch subs[1] {
case "repository":
cr.Spec.Git.Repository = args[1]
case "accessToken":
cr.Spec.Git.AccessToken = args[1]
case "secretName":
cr.Spec.Git.SecretName = args[1]
case "userName":
cr.Spec.Git.UserName = args[1]
default:
return errors.New(arg + " does not match any cr spec")
}
return nil
}
func (q *Qliksense) processSetOpsRunner(arg string, cr *api.QliksenseCR) error {
args := strings.Split(arg, "=")
subs := strings.Split(args[0], ".")
if cr.Spec.OpsRunner == nil {
cr.Spec.OpsRunner = &config.OpsRunner{}
}
switch subs[1] {
case "enabled":
if args[1] != "yes" && args[1] != "no" {
return errors.New("Please use yes or no for key enabled")
}
cr.Spec.OpsRunner.Enabled = args[1]
case "schedule":
if _, err := cron.ParseStandard(args[1]); err != nil {
return errors.New("Please enter string with standard cron scheduling syntax ")
}
cr.Spec.OpsRunner.Schedule = args[1]
case "watchBranch":
cr.Spec.OpsRunner.WatchBranch = args[1]
case "image":
cr.Spec.OpsRunner.Image = args[1]
default:
return errors.New(arg + " does not match any cr spec")
}
return nil
}
// SetContextConfig - set the context for qliksense kubernetes resources to live in
func (q *Qliksense) SetContextConfig(args []string) error {
if len(args) == 1 {
err := q.SetUpQliksenseContext(args[0])
if err != nil {
return err
}
} else {
err := fmt.Errorf("Please provide a name to configure the context with")
log.Println(err)
return err
}
return nil
}
func (q *Qliksense) ListContextConfigs() error {
qliksenseConfigFile := filepath.Join(q.QliksenseHome, QliksenseConfigFile)
var qliksenseConfig api.QliksenseConfig
if err := api.ReadFromFile(&qliksenseConfig, qliksenseConfigFile); err != nil {
log.Println(err)
return err
}
out := ansi.NewColorableStdout()
w := tabwriter.NewWriter(out, 5, 8, 0, '\t', 0)
fmt.Fprintln(w, Underline("Context Name"), "\t", Underline("CR File Location"))
w.Flush()
if len(qliksenseConfig.Spec.Contexts) > 0 {
for _, cont := range qliksenseConfig.Spec.Contexts {
fmt.Fprintln(w, cont.Name, "\t", qliksenseConfig.GetCRFilePath(cont.Name), "\t")
}
w.Flush()
fmt.Fprintln(out, "")
fmt.Fprintln(out, Bold("Current Context : "), qliksenseConfig.Spec.CurrentContext)
} else {
fmt.Fprintln(out, "No Contexts Available")
}
return nil
}
func (q *Qliksense) DeleteContextConfig(args []string, flag bool) error {
if len(args) == 1 {
qliksenseConfigFile := filepath.Join(q.QliksenseHome, QliksenseConfigFile)
var qliksenseConfig api.QliksenseConfig
api.ReadFromFile(&qliksenseConfig, qliksenseConfigFile)
out := ansi.NewColorableStdout()
switch args[0] {
case qliksenseConfig.Spec.CurrentContext:
fmt.Fprintln(out, Yellow("Please switch contexts to be able to delete this context."))
err := fmt.Errorf(Red("Cannot delete current context - %s").String(), White(Bold(qliksenseConfig.Spec.CurrentContext)))
return err
case DefaultQliksenseContext:
err := fmt.Errorf(Red("Cannot delete default qliksense context").String())
return err
default:
qliksenseContextsDir1 := filepath.Join(q.QliksenseHome, QliksenseContextsDir)
qliksenseContextFile := filepath.Join(qliksenseContextsDir1, args[0])
qliksenseSecretsDir1 := filepath.Join(q.QliksenseHome, QliksenseSecretsDir, QliksenseContextsDir)
qliksenseSecretsFile := filepath.Join(qliksenseSecretsDir1, args[0])
if err := os.RemoveAll(qliksenseContextFile); err != nil {
err = fmt.Errorf("Not able to delete %s dir: %v", qliksenseContextsDir1, err)
log.Println(err)
return err
} else if err := os.RemoveAll(qliksenseSecretsFile); err != nil {
err = fmt.Errorf("No Secrets Folder Detected")
log.Println(err)
return err
} else {
currentLength := len(qliksenseConfig.Spec.Contexts)
if currentLength > 0 {
temp := qliksenseConfig.Spec.Contexts
qliksenseConfig.Spec.Contexts = nil
for _, ctx := range temp {
if ctx.Name != args[0] {
qliksenseConfig.Spec.Contexts = append(qliksenseConfig.Spec.Contexts, api.Context{
Name: ctx.Name,
CrFile: ctx.CrFile,
})
}
}
newLength := len(qliksenseConfig.Spec.Contexts)
if currentLength != newLength {
ans := flag
if ans == false {
ans = AskForConfirmation("Are You Sure? ")
}
if ans == true {
api.WriteToFile(&qliksenseConfig, qliksenseConfigFile)
fmt.Fprintln(out, Yellow(Underline("Warning: Active resources may still be running in-cluster")))
fmt.Fprintln(out, Green("Successfully deleted context: "), Bold(args[0]))
} else {
return nil
}
} else {
err := fmt.Errorf(Red("Context not found").String())
return err
}
}
}
}
} else {
err := fmt.Errorf("Please provide a context as an argument to delete")
log.Println(err)
return err
}
return nil
}
// SetUpQliksenseDefaultContext - to setup dir structure for default qliksense context
func (q *Qliksense) SetUpQliksenseDefaultContext() error {
if api.FileExists(filepath.Join(q.QliksenseHome, "config.yaml")) {
qliksenseConfig := api.NewQConfig(q.QliksenseHome)
if qliksenseConfig.IsContextExist(DefaultQliksenseContext) {
return nil
}
}
return q.SetUpQliksenseContext(DefaultQliksenseContext)
}
// SetUpQliksenseContext - to setup qliksense context
func (q *Qliksense) SetUpQliksenseContext(contextName string) error {
if contextName == "" {
err := fmt.Errorf("Please enter a non-empty context-name")
log.Println(err)
return err
}
// check the length of the context name entered by the user, it should not exceed 17 chars
if len(contextName) > MaxContextNameLength {
err := fmt.Errorf("Please enter a context-name with utmost 17 characters")
log.Println(err)
return err
}
qliksenseConfigFile := filepath.Join(q.QliksenseHome, QliksenseConfigFile)
qliksenseConfig := api.NewQConfigEmpty(q.QliksenseHome)
if !api.FileExists(qliksenseConfigFile) {
qliksenseConfig.AddBaseQliksenseConfigs(contextName)
} else {
if err := api.ReadFromFile(qliksenseConfig, qliksenseConfigFile); err != nil {
log.Println(err)
return err
}
}
if qliksenseConfig.IsContextExist(contextName) {
qliksenseConfig.Spec.CurrentContext = contextName
return qliksenseConfig.Write()
}
qliksenseCR := &api.QliksenseCR{}
qliksenseCR.AddCommonConfig(contextName)
qliksenseConfig.Spec.CurrentContext = contextName
if err := qliksenseConfig.CreateOrWriteCrAndContext(qliksenseCR); err != nil {
return err
}
// set the encrypted default mongo
return q.SetSecrets([]string{`qliksense.mongodbUri="mongodb://qlik-default-mongodb:27017/qliksense?ssl=false"`}, false, false)
}
func validateInput(input string) (string, error) {
var err error
validInputs := []string{"yes", "no", "None"}
isValid := false
for _, elem := range validInputs {
if input == elem {
isValid = true
break
}
}
if !isValid {
err = fmt.Errorf("Please enter one of: yes, no or None")
log.Println(err)
}
return input, err
}
// PrepareK8sSecret targetFile contains base64 encoded value of encrypted value.
// this method decodes and decrypts the secret value in the secret.yaml file and returns a B64encoded string
func (q *Qliksense) PrepareK8sSecret(targetFile string) (string, error) {
// check if targetFile exists
if !api.FileExists(targetFile) {
err := fmt.Errorf("Target file does not exist in the path provided")
log.Println(err)
return "", err
}
qConfig := api.NewQConfig(q.QliksenseHome)
encryptionKey, err := qConfig.GetEncryptionKeyForCurrent()
if err != nil {
return "", err
}
// read the target file
k8sSecret, err := readTargetfile(targetFile)
if err != nil {
return "", err
}
// retrieve value from data section
k8sSecret1, err := api.K8sSecretFromYaml(k8sSecret)
if err != nil {
return "", err
}
dataMap := k8sSecret1.Data
var resultMap = make(map[string][]byte)
for k, v := range dataMap {
//k8s secrets has already base64 decoed value
decryptedString, err := api.DecryptData(v, encryptionKey)
if err != nil {
err := fmt.Errorf("Not able to decrypt message: %v", err)
return "", err
}
resultMap[k] = []byte(decryptedString)
}
// putting the above map back into the k8sSecret struct
k8sSecret1.Data = resultMap
k8sSecretBytes, err := api.K8sSecretToYaml(k8sSecret1)
if err != nil {
return "", err
}
return string(k8sSecretBytes), nil
}
func readTargetfile(targetFile string) ([]byte, error) {
k8sSecret, err := ioutil.ReadFile(targetFile)
if err != nil {
err := fmt.Errorf("Unable to read the targetFile")
log.Println(err)
return nil, err
}
return k8sSecret, nil
}
func (q *Qliksense) SetImageRegistry(registry, pushUsername, pushPassword, pullUsername, pullPassword string) error {
qConfig := api.NewQConfig(q.QliksenseHome)
qliksenseCR, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
if pushUsername != "" {
if err := qConfig.SetPushDockerConfigJsonSecret(&api.DockerConfigJsonSecret{
Uri: registry,
Username: pushUsername,
Password: pushPassword,
}); err != nil {
return err
} else if err := qConfig.SetPullDockerConfigJsonSecret(&api.DockerConfigJsonSecret{
Name: pullSecretName,
Uri: registry,
Username: pullUsername,
Password: pullPassword,
Email: pullUsername,
}); err != nil {
return err
}
} else if err := qConfig.DeletePushDockerConfigJsonSecret(); err != nil && !os.IsNotExist(err) {
return err
} else if err := qConfig.DeletePullDockerConfigJsonSecret(); err != nil && !os.IsNotExist(err) {
return err
}
qliksenseCR.Spec.AddToConfigs("qliksense", imageRegistryConfigKey, registry)
return qConfig.WriteCR(qliksenseCR)
}
func (q *Qliksense) SetEulaAccepted() error {
qConfig := api.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
if !qcr.IsEULA() {
qcr.SetEULA("yes")
return qConfig.WriteCurrentContextCR(qcr)
}
return nil
}

View File

@@ -1,865 +0,0 @@
package qliksense
import (
"encoding/base64"
b64 "encoding/base64"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/qlik-oss/k-apis/pkg/config"
"github.com/qlik-oss/sense-installer/pkg/api"
"gopkg.in/yaml.v2"
)
const (
testDir = "./tests"
qlikDefaultContext = "qlik-default"
secrets = "secrets"
contexts = "contexts"
)
var targetFileStringTemplate = `
apiVersion: v1
data:
mongodbUri: %s
kind: Secret
metadata:
name: testctx-qliksense-senseinstaller
type: Opaque
`
var decText = "mongodb://qlik-default-mongodb:27017/qliksense?ssl=false"
func setupTargetFileAndPrivateKey() (string, string, error) {
secretKeyLocation := filepath.Join(testDir, secrets, contexts, qlikDefaultContext, secrets)
if err := os.MkdirAll(secretKeyLocation, 0777); err != nil {
err = fmt.Errorf("Not able to create directories")
log.Fatal(err)
}
os.Setenv("QLIKSENSE_KEY_LOCATION", secretKeyLocation)
//privKeyFile := filepath.Join(secretKeyLocation, "user_secret_key")
key, err := api.LoadSecretKey(secretKeyLocation)
if key == "" {
key, err = api.GenerateAndStoreSecretKey(secretKeyLocation)
}
encData, _ := api.EncryptData([]byte(decText), key)
encText := b64.StdEncoding.EncodeToString(encData)
targetFileString := fmt.Sprintf(targetFileStringTemplate, encText)
targetFile := filepath.Join(testDir, "targetfile.yaml")
// tests/config.yaml exists
err = ioutil.WriteFile(targetFile, []byte(targetFileString), 0777)
if err != nil {
log.Printf("Error while creating file: %v", err)
return "", "", err
}
return targetFile, key, err
}
func setup() func() {
// create tests dir
os.RemoveAll(testDir)
if err := os.Mkdir(testDir, 0777); err != nil {
log.Printf("\nError occurred: %v", err)
}
config :=
`
apiVersion: config.qlik.com/v1
kind: QliksenseConfig
metadata:
name: qliksenseConfig
spec:
contexts:
- name: qlik-default
crFile: contexts/qlik-default/qlik-default.yaml
currentContext: qlik-default
`
configFile := filepath.Join(testDir, "config.yaml")
// tests/config.yaml exists
ioutil.WriteFile(configFile, []byte(config), 0777)
contextYaml :=
`
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
spec:
profile: docker-desktop
rotateKeys: "yes"
releaseName: qlik-default
`
qlikDefaultContext := "qlik-default"
// create contexts/qlik-default/ under tests/
contexts := "contexts"
contextsDir := filepath.Join(testDir, contexts, qlikDefaultContext)
if err := os.MkdirAll(contextsDir, 0777); err != nil {
err = fmt.Errorf("Not able to create directories")
log.Fatal(err)
}
contextFile := filepath.Join(contextsDir, qlikDefaultContext+".yaml")
ioutil.WriteFile(contextFile, []byte(contextYaml), 0777)
tearDown := func() {
os.RemoveAll(testDir)
}
return tearDown
}
func readCRFile() (*api.QliksenseCR, error) {
qlikDefaultContext := "qlik-default"
qliksenseCR := &api.QliksenseCR{}
contextFileContents, err := ioutil.ReadFile(filepath.Join(testDir, contexts, qlikDefaultContext, qlikDefaultContext+".yaml"))
if err != nil {
log.Println(err)
err = fmt.Errorf("Not able to read current context info")
return nil, err
}
if err := yaml.Unmarshal(contextFileContents, qliksenseCR); err != nil {
err = fmt.Errorf("An error occurred during unmarshalling: %v", err)
return nil, err
}
return qliksenseCR, nil
}
func Test_retrieveCurrentContextInfo(t *testing.T) {
tearDown := setup()
defer tearDown()
q := &Qliksense{
QliksenseHome: testDir,
}
qConfig := api.NewQConfig(q.QliksenseHome)
_, err := qConfig.GetCurrentCR()
if err != nil {
t.FailNow()
}
}
func TestSetUpQliksenseContext(t *testing.T) {
type args struct {
qlikSenseHome string
contextName string
isDefaultContext bool
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "valid contextname",
args: args{
qlikSenseHome: testDir,
contextName: "testContext1",
isDefaultContext: false,
},
wantErr: false,
},
{
name: "invalid contextname",
args: args{
qlikSenseHome: testDir,
contextName: "testContext_abcdefgh",
isDefaultContext: false,
},
wantErr: true,
},
{
name: "empty contextname",
args: args{
qlikSenseHome: testDir,
contextName: "",
isDefaultContext: false,
},
wantErr: true,
},
}
tearDown := setup()
defer tearDown()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
q := New(tt.args.qlikSenseHome)
if err := q.SetUpQliksenseContext(tt.args.contextName); (err != nil) != tt.wantErr {
t.Errorf("SetUpQliksenseContext() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestSetUpQliksenseDefaultContext(t *testing.T) {
type args struct {
qlikSenseHome string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "valid case",
args: args{
qlikSenseHome: testDir,
},
wantErr: false,
},
}
tearDown := setup()
defer tearDown()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
q := New(tt.args.qlikSenseHome)
if err := q.SetUpQliksenseDefaultContext(); (err != nil) != tt.wantErr {
t.Errorf("SetUpQliksenseDefaultContext() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestSetOtherConfigs(t *testing.T) {
type args struct {
q *Qliksense
args []string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "valid case",
args: args{
q: &Qliksense{
QliksenseHome: testDir,
},
args: []string{"profile=minikube", "rotateKeys=yes", "storageClassName=efs", "opsRunner.enabled=yes", "opsRunner.schedule=30 * * * *", "git.repository=master", "git.userName=foo", "git.accessToken=1234"},
},
wantErr: false,
},
{
name: "invalid configs",
args: args{
q: &Qliksense{
QliksenseHome: testDir,
},
args: []string{"someconfig=somevalue, opsRunner.schedule=bar", "opsRunner.enabled=bar", "git.foo=bar", "rotateKeys=bar"},
},
wantErr: true,
},
{
name: "empty configs",
args: args{
q: &Qliksense{
QliksenseHome: testDir,
},
args: []string{},
},
wantErr: true,
},
}
tearDown := setup()
defer tearDown()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.args.q.SetOtherConfigs(tt.args.args); (err != nil) != tt.wantErr {
t.Errorf("SetOtherConfigs() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestSetConfigs(t *testing.T) {
type args struct {
q *Qliksense
args []string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "valid case",
args: args{
q: &Qliksense{
QliksenseHome: testDir,
},
args: []string{"qliksense.acceptEULA=\"yes\"", "qliksense.mongodbUri=\"mongo://mongo:3307\""},
},
wantErr: false,
},
}
tearDown := setup()
defer tearDown()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.args.q.SetConfigs(tt.args.args, false); (err != nil) != tt.wantErr {
t.Errorf("SetConfigs() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestSetImageRegistry(t *testing.T) {
getQlikSense := func(tmpQlikSenseHome string) (*Qliksense, error) {
if err := ioutil.WriteFile(path.Join(tmpQlikSenseHome, "config.yaml"), []byte(`
apiVersion: config.qlik.com/v1
kind: QliksenseConfig
metadata:
name: QliksenseConfigMetadata
spec:
contexts:
- name: qlik-default
crFile: contexts/qlik-default/qlik-default.yaml
currentContext: qlik-default
`), os.ModePerm); err != nil {
return nil, err
}
defaultContextDir := path.Join(tmpQlikSenseHome, "contexts", "qlik-default")
if err := os.MkdirAll(defaultContextDir, os.ModePerm); err != nil {
return nil, err
}
version := "foo"
manifestsRootDir := fmt.Sprintf("%s/repo/%s", defaultContextDir, version)
if err := ioutil.WriteFile(path.Join(defaultContextDir, "qlik-default.yaml"), []byte(fmt.Sprintf(`
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
labels:
version: %s
spec:
profile: docker-desktop
manifestsRoot: %s
namespace: some-namespace
`, version, manifestsRootDir)), os.ModePerm); err != nil {
return nil, err
}
return &Qliksense{
QliksenseHome: tmpQlikSenseHome,
}, nil
}
testCases := []struct {
name string
registry string
pushUsername string
pushPassword string
pullUsername string
pullPassword string
expectSecretsExist bool
}{
{
name: "no auth",
registry: "foobar",
pushUsername: "",
pushPassword: "",
pullUsername: "",
pullPassword: "",
expectSecretsExist: false,
},
{
name: "auth",
registry: "foobar",
pushUsername: "foo-push",
pushPassword: "bar-push",
pullUsername: "foo-pull",
pullPassword: "bar-pull",
expectSecretsExist: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
tmpQlikSenseHome, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer os.RemoveAll(tmpQlikSenseHome)
q, err := getQlikSense(tmpQlikSenseHome)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := q.SetImageRegistry(testCase.registry, testCase.pushUsername, testCase.pushPassword,
testCase.pullUsername, testCase.pullPassword); err != nil {
t.Fatalf("unexpected error: %v", err)
}
qConfig := api.NewQConfig(q.QliksenseHome)
if testCase.expectSecretsExist {
if pushSecret, err := qConfig.GetPushDockerConfigJsonSecret(); err != nil {
t.Fatalf("unexpected error: %v", err)
} else if pushSecret.Uri != testCase.registry ||
pushSecret.Username != testCase.pushUsername || pushSecret.Password != testCase.pushPassword {
t.Fatalf("unexpected push secret content: %v", pushSecret)
}
if pullSecret, err := qConfig.GetPullDockerConfigJsonSecret(); err != nil {
t.Fatalf("unexpected error: %v", err)
} else if pullSecret.Uri != testCase.registry ||
pullSecret.Name != "artifactory-docker-secret" ||
pullSecret.Username != testCase.pullUsername || pullSecret.Password != testCase.pullPassword {
t.Fatalf("unexpected pull secret content: %v", pullSecret)
}
} else {
if _, err := qConfig.GetPushDockerConfigJsonSecret(); err == nil {
t.Fatal("unexpected image-registry-push-secret.yaml")
} else if _, err := qConfig.GetPullDockerConfigJsonSecret(); err == nil {
t.Fatal("unexpected image-registry-pull-secret.yaml")
}
}
})
}
}
func removePrivateKey() {
err := os.Remove(filepath.Join(testDir, secrets, contexts, qlikDefaultContext, secrets, "user_secret_key"))
if err != nil {
log.Fatalf("Could not delete private key %v", err)
}
return
}
func Test_PrepareK8sSecret(t *testing.T) {
type fields struct {
QliksenseHome string
}
tests := []struct {
name string
fields fields
want string
wantErr bool
setup func() (string, func())
}{
{
name: "valid case",
fields: fields{
QliksenseHome: testDir,
},
want: fmt.Sprintf(targetFileStringTemplate, base64.StdEncoding.EncodeToString([]byte(decText))),
wantErr: false,
setup: func() (string, func()) {
tearDown := setup()
targetFile, _, _ := setupTargetFileAndPrivateKey()
return targetFile, tearDown
},
},
{
name: "private key not supplied should result in decryption error",
fields: fields{
QliksenseHome: testDir,
},
want: "",
wantErr: true,
setup: func() (string, func()) {
tearDown := setup()
targetFile, _, _ := setupTargetFileAndPrivateKey()
removePrivateKey()
return targetFile, tearDown
},
},
{
name: "target file not supplied",
fields: fields{
QliksenseHome: testDir,
},
want: "",
wantErr: true,
setup: func() (string, func()) {
tearDown := setup()
setupTargetFileAndPrivateKey()
return "", tearDown
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
targetFile, tearDown := tt.setup()
q := &Qliksense{
QliksenseHome: tt.fields.QliksenseHome,
}
got, err := q.PrepareK8sSecret(targetFile)
if (err != nil) != tt.wantErr {
t.Errorf("Qliksense.PrepareK8sSecret() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(strings.TrimSpace(got), strings.TrimSpace(tt.want)) {
t.Errorf("Qliksense.PrepareK8sSecret() = %v, want %v", got, tt.want)
}
tearDown()
})
}
}
func Test_ListContextConfigs(t *testing.T) {
type fields struct {
QliksenseHome string
}
tests := []struct {
name string
fields fields
wantErr bool
setup func() (string, func())
}{
{
name: "valid case",
fields: fields{
QliksenseHome: testDir,
},
wantErr: false,
setup: func() (string, func()) {
tearDown := setup()
return "", tearDown
},
},
{
name: "config yaml does not exist",
fields: fields{
QliksenseHome: testDir,
},
wantErr: true,
setup: func() (string, func()) {
return "", func() {}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, tearDown := tt.setup()
q := &Qliksense{
QliksenseHome: tt.fields.QliksenseHome,
}
if err := q.ListContextConfigs(); (err != nil) != tt.wantErr {
t.Errorf("ListContextConfigs() error = %v, wantErr %v", err, tt.wantErr)
}
tearDown()
})
}
}
func Test_SetSecrets(t *testing.T) {
type fields struct {
QliksenseHome string
}
type args struct {
args []string
isSecretSet bool
base64 bool
}
tests := []struct {
name string
fields fields
args args
wantErr bool
}{
{
name: "valid secret secrets=false",
fields: fields{
QliksenseHome: testDir,
},
args: args{
args: []string{"qliksense.mongodbUri=\"mongodb://qlik-default-mongodb:27017/qliksense?ssl=false\""},
isSecretSet: false,
},
wantErr: false,
},
{
name: "valid secret secrets=false base64 encoded",
fields: fields{
QliksenseHome: testDir,
},
args: args{
args: []string{"qliksense.mongodbUri=bW9uZ29kYjovL3FsaWstZGVmYXVsdC1tb25nb2RiOjI3MDE3L3FsaWtzZW5zZT9zc2w9ZmFsc2U="},
isSecretSet: false,
base64: true,
},
wantErr: false,
},
{
name: "test1 valid secret secrets=true",
fields: fields{
QliksenseHome: testDir,
},
args: args{
args: []string{"qliksense.mongodbUri=\"mongo://mongo:3307\""},
isSecretSet: true,
},
wantErr: false,
},
{
name: "test2 valid secret secrets=true",
fields: fields{
QliksenseHome: testDir,
},
args: args{
args: []string{"qliksense.mongodbUri=\"mongodb://qlik-default-mongodb:27017/qliksense?ssl=false\""},
isSecretSet: true,
},
wantErr: false,
},
{
name: "invalid secret secrets=false",
fields: fields{
QliksenseHome: testDir,
},
args: args{
args: []string{},
isSecretSet: false,
},
wantErr: true,
},
}
tearDown := setup()
_, encryptionKey, err := setupTargetFileAndPrivateKey()
if err != nil {
t.FailNow()
}
defer tearDown()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
q := &Qliksense{
QliksenseHome: tt.fields.QliksenseHome,
}
if err := q.SetSecrets(tt.args.args, tt.args.isSecretSet, tt.args.base64); (err != nil) != tt.wantErr {
t.Errorf("SetSecrets() error = %v, wantErr %v", err, tt.wantErr)
t.FailNow()
}
if tt.wantErr || len(tt.args.args) == 0 {
return
}
// VERIFICATION PART BELOW
// extract the value for testing
testValueArr := strings.SplitN(tt.args.args[0], "=", 2)
testValue := strings.ReplaceAll(testValueArr[1], "\"", "")
if tt.args.base64 {
d, _ := b64.StdEncoding.DecodeString(testValue)
testValue = strings.Trim(string(d), "\n ")
}
qliksenseCR, err := readCRFile()
if err != nil {
err = fmt.Errorf("Not able to read from context file: %v", err)
log.Println(err)
t.FailNow()
}
for svcName := range qliksenseCR.Spec.Secrets { // we are sure we only have one service
for _, v := range qliksenseCR.Spec.Secrets {
for _, item := range v { // we are sure we only have one entry
valToBeEncrypted, err := getValueToBeDecodedForSetSecrets(item, qliksenseCR, svcName)
if err != nil {
err := fmt.Errorf("Error occurred while decoding: %v", err)
log.Printf("decode error: %v", err)
t.FailNow()
}
decryptedVal, err := api.DecryptData([]byte(valToBeEncrypted), encryptionKey)
if err != nil {
err := fmt.Errorf("Error occurred while testing decryption: %v", err)
log.Printf("No Data in Secret: %v", err)
t.FailNow()
}
if string(decryptedVal) != testValue {
t.FailNow()
}
}
}
}
})
}
}
func getValueToBeDecodedForSetSecrets(item config.NameValue, qliksenseCR *api.QliksenseCR, svcName string) (string, error) {
if item.ValueFrom != nil && item.ValueFrom.SecretKeyRef != nil {
// secret=true
secretFilePath := filepath.Join(testDir, contexts, qliksenseCR.GetName(), QliksenseSecretsDir, svcName+".yaml")
if api.FileExists(secretFilePath) {
secretFileContents, err := ioutil.ReadFile(secretFilePath)
if err != nil {
err = fmt.Errorf("An error occurred during unmarshalling: %v", err)
return "", err
}
k8sSecret, err := api.K8sSecretFromYaml(secretFileContents)
if err != nil {
err = fmt.Errorf("An error occurred during unmarshalling: %v", err)
return "", err
}
if k8sSecret.Data == nil {
err = fmt.Errorf("No Data in Secret: %v", err)
return "", err
}
return string(k8sSecret.Data[item.ValueFrom.SecretKeyRef.Key]), nil
}
}
// secret=false
if item.Value != "" {
b, err := b64.RawStdEncoding.DecodeString(item.Value)
return string(b), err
}
err := fmt.Errorf("Both Value and ValueFrom are empty")
return "", err
}
func setupDeleteContext() func() {
if err := os.Mkdir(testDir, 0777); err != nil {
log.Printf("\nError occurred: %v", err)
}
config :=
`
apiVersion: config.qlik.com/v1
kind: QliksenseConfig
metadata:
name: qliksenseConfig
spec:
contexts:
- name: qlik-default
crFile: contexts/qlik-default.yaml
- name: qlik1
crFile: contexts/qlik1.yaml
- name: qlik2
crFile: contexts/qlik2.yaml
currentContext: qlik1
`
configFile := filepath.Join(testDir, "config.yaml")
// tests/config.yaml exists
ioutil.WriteFile(configFile, []byte(config), 0777)
contextYaml :=
`
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
spec:
profile: docker-desktop
rotateKeys: "yes"
releaseName: qlik-default
`
qlikDefaultContext := "qlik-default"
// create contexts/qlik-default/ under tests/
contexts := "contexts"
contextsDir1 := filepath.Join(testDir, contexts, qlikDefaultContext)
if err := os.MkdirAll(contextsDir1, 0777); err != nil {
err = fmt.Errorf("Not able to create directories")
log.Fatal(err)
}
contextYaml1 :=
`
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik1
spec:
profile: docker-desktop
rotateKeys: "yes"
releaseName: qlik1`
contextYaml2 :=
`
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik2
spec:
profile: docker-desktop
rotateKeys: "yes"
releaseName: qlik2`
contextsDir := filepath.Join(testDir, contexts, "qlik1")
if err := os.MkdirAll(contextsDir, 0777); err != nil {
err = fmt.Errorf("Not able to create directories")
log.Fatal(err)
}
contextsDir2 := filepath.Join(testDir, contexts, "qlik2")
if err := os.MkdirAll(contextsDir2, 0777); err != nil {
err = fmt.Errorf("Not able to create directories")
log.Fatal(err)
}
contextFile := filepath.Join(contextsDir, "qlik1.yaml")
ioutil.WriteFile(contextFile, []byte(contextYaml1), 0777)
contextFile2 := filepath.Join(contextsDir2, "qlik2.yaml")
ioutil.WriteFile(contextFile2, []byte(contextYaml2), 0777)
contextFile1 := filepath.Join(contextsDir1, "qlik-default.yaml")
ioutil.WriteFile(contextFile1, []byte(contextYaml), 0777)
tearDown := func() {
os.RemoveAll(testDir)
}
return tearDown
}
func TestDeleteContexts(t *testing.T) {
type args struct {
qlikSenseHome string
contextName string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "valid context",
args: args{
qlikSenseHome: testDir,
contextName: "qlik2",
},
wantErr: false,
},
{
name: "default context",
args: args{
qlikSenseHome: testDir,
contextName: "qlik-default",
},
wantErr: true,
},
{
name: "non-existent context",
args: args{
qlikSenseHome: testDir,
contextName: "qlik3",
},
wantErr: true,
},
{
name: "current context",
args: args{
qlikSenseHome: testDir,
contextName: "qlik1",
},
wantErr: true,
},
}
tearDown := setupDeleteContext()
defer tearDown()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
q := New(tt.args.qlikSenseHome)
var arg []string
arg = append(arg, tt.args.contextName)
if err := q.DeleteContextConfig(arg, true); (err != nil) != tt.wantErr {
t.Errorf("DeleteContext() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}

View File

@@ -1,109 +0,0 @@
package qliksense
import (
"fmt"
"strings"
"reflect"
kconfig "github.com/qlik-oss/k-apis/pkg/config"
"github.com/qlik-oss/sense-installer/pkg/api"
)
func (q *Qliksense) UnsetCmd(args []string) error {
return unsetAll(q.QliksenseHome, args)
}
func unsetAll(qHome string, args []string) error {
qConfig := api.NewQConfig(qHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
// either delete all args or none
for _, arg := range args {
isRemoved := false
// delete if key present
if !strings.Contains(arg, ".") {
if isRemoved = unsetOnlyKey(arg, qcr); isRemoved {
//continue to the next arg
continue
} else if isRemoved = unsetServiceName(arg, qcr); isRemoved {
//continue to the next arg
continue
} else {
return fmt.Errorf("%s not found in the context", arg)
}
}
// delete key inside configs if present
// delete key inside secrets if present
if isRemoved = unsetServiceKey(arg, qcr); !isRemoved {
return fmt.Errorf("%s not found in the context", arg)
}
}
return qConfig.WriteCR(qcr)
}
func unsetOnlyKey(key string, qcr *api.QliksenseCR) bool {
v := reflect.ValueOf(qcr.Spec).Elem().FieldByName(strings.Title(key))
if v.IsValid() && v.CanSet() {
v.SetString("")
return true
}
return false
}
func unsetServiceName(svc string, qcr *api.QliksenseCR) bool {
if qcr.Spec.Configs != nil && qcr.Spec.Configs[svc] != nil {
delete(qcr.Spec.Configs, svc)
return true
}
if qcr.Spec.Secrets != nil && qcr.Spec.Secrets[svc] != nil {
delete(qcr.Spec.Secrets, svc)
return true
}
return false
}
func unsetServiceKey(svcKey string, qcr *api.QliksenseCR) bool {
sk := strings.Split(svcKey, ".")
svc := sk[0]
key := sk[1]
if qcr.Spec.Configs != nil && qcr.Spec.Configs[svc] != nil {
index := findIndex(key, qcr.Spec.Configs[svc])
if index > -1 {
qcr.Spec.Configs[svc][index] = qcr.Spec.Configs[svc][len(qcr.Spec.Configs[svc])-1]
qcr.Spec.Configs[svc] = qcr.Spec.Configs[svc][:len(qcr.Spec.Configs[svc])-1]
if len(qcr.Spec.Configs[svc]) == 0 {
delete(qcr.Spec.Configs, svc)
}
return true
}
}
if qcr.Spec.Secrets != nil && qcr.Spec.Secrets[svc] != nil {
index := findIndex(key, qcr.Spec.Secrets[svc])
if index > -1 {
qcr.Spec.Secrets[svc][index] = qcr.Spec.Secrets[svc][len(qcr.Spec.Secrets[svc])-1]
qcr.Spec.Secrets[svc] = qcr.Spec.Secrets[svc][:len(qcr.Spec.Secrets[svc])-1]
if len(qcr.Spec.Secrets[svc]) == 0 {
delete(qcr.Spec.Secrets, svc)
}
return true
}
}
return false
}
func findIndex(elem string, nvs kconfig.NameValues) int {
for i, nv := range nvs {
if nv.Name == elem {
return i
}
}
return -1
}

View File

@@ -1,99 +0,0 @@
package qliksense
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/qlik-oss/sense-installer/pkg/api"
_ "gopkg.in/yaml.v2"
)
func TestUnsetAll(t *testing.T) {
qHome, _ := ioutil.TempDir("", "")
testPepareDir(qHome)
defer os.RemoveAll(qHome)
//fmt.Print(qHome)
args := []string{"rotateKeys", "qliksense", "qliksense2.acceptEula3", "serviceA.acceptEula"}
if err := unsetAll(qHome, args); err != nil {
t.Log("error during unset", err)
t.FailNow()
}
qc := api.NewQConfig(qHome)
qcr, err := qc.GetCurrentCR()
if err != nil {
t.Log("error while getting current cr", err)
t.FailNow()
}
if qcr.Spec.RotateKeys != "" {
t.Log("Expected empty rotateKeys but got: " + qcr.Spec.RotateKeys)
t.Fail()
}
if qcr.Spec.Configs["qliksense"] != nil {
t.Log("qliksense in configs not deleted")
t.Fail()
}
if len(qcr.Spec.Configs["qliksense2"]) != 1 {
t.Log("qliksense2.acceptEula3 not deleted")
t.Fail()
}
if qcr.Spec.Configs["serviceA"] != nil {
t.Log("serviceA not deleted")
t.Fail()
}
}
func testPepareDir(qHome string) {
config :=
`
apiVersion: config.qlik.com/v1
kind: QliksenseConfig
metadata:
name: qliksenseConfig
spec:
contexts:
- name: qlik-default
crFile: contexts/qlik-default/qlik-default.yaml
currentContext: qlik-default
`
configFile := filepath.Join(qHome, "config.yaml")
// tests/config.yaml exists
ioutil.WriteFile(configFile, []byte(config), 0777)
contextYaml :=
`
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
spec:
profile: docker-desktop
rotateKeys: "yes"
configs:
qliksense:
- name: acceptEula
value: some
qliksense2:
- name: acceptEula2
value: some
- name: acceptEula3
value: some
serviceA:
- name: acceptEula
value: some
`
qlikDefaultContext := "qlik-default"
// create contexts/qlik-default/ under tests/
contexts := "contexts"
contextsDir := filepath.Join(qHome, contexts, qlikDefaultContext)
if err := os.MkdirAll(contextsDir, 0777); err != nil {
err = fmt.Errorf("Not able to create directories")
}
contextFile := filepath.Join(contextsDir, qlikDefaultContext+".yaml")
ioutil.WriteFile(contextFile, []byte(contextYaml), 0777)
}

View File

@@ -1,194 +0,0 @@
package qliksense
import (
"fmt"
"os"
"path/filepath"
"github.com/mitchellh/go-homedir"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
apixv1beta1client "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
)
type CrdCommandOptions struct {
All bool
}
func (q *Qliksense) ViewCrds(opts *CrdCommandOptions) error {
//io.WriteString(os.Stdout, q.GetCRDString())
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
fmt.Println("cannot get the current-context cr", err)
return err
}
engineCRD, err := getQliksenseInitCrds(qcr)
if err != nil {
return err
}
customCrd, err := getCustomCrds(qcr)
if err != nil {
return nil
}
fmt.Println(engineCRD)
if customCrd != "" {
fmt.Println("---")
fmt.Println(customCrd)
}
if opts.All {
fmt.Println("---")
fmt.Printf("%s", q.GetOperatorCRDString())
}
return nil
}
func (q *Qliksense) InstallCrds(opts *CrdCommandOptions) error {
// install qliksense-init crd
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
fmt.Println("cannot get the current-context cr", err)
return err
}
if engineCRD, err := getQliksenseInitCrds(qcr); err != nil {
return err
} else if err = qapi.KubectlApply(engineCRD, ""); err != nil {
return err
}
if customCrd, err := getCustomCrds(qcr); err != nil {
return err
} else if customCrd != "" {
if err = qapi.KubectlApply(customCrd, ""); err != nil {
return err
}
}
if opts.All { // install opeartor crd
if err := qapi.KubectlApply(q.GetOperatorCRDString(), ""); err != nil {
fmt.Println("cannot do kubectl apply on opeartor CRD", err)
return err
}
}
return nil
}
func getQliksenseInitCrds(qcr *qapi.QliksenseCR) (string, error) {
var repoPath string
var err error
if qcr.Spec.GetManifestsRoot() != "" {
repoPath = qcr.Spec.GetManifestsRoot()
} else {
if repoPath, err = DownloadFromGitRepoToTmpDir(defaultConfigRepoGitUrl, "master"); err != nil {
return "", err
}
}
qInitMsPath := filepath.Join(repoPath, Q_INIT_CRD_PATH)
if _, err := os.Lstat(qInitMsPath); err != nil {
// older version of qliksense-init used
qInitMsPath = filepath.Join(repoPath, "manifests/base/manifests/qliksense-init")
}
qInitByte, err := ExecuteKustomizeBuild(qInitMsPath)
if err != nil {
fmt.Println("cannot generate crds for qliksense-init", err)
return "", err
}
return string(qInitByte), nil
}
func getCustomCrds(qcr *qapi.QliksenseCR) (string, error) {
crdPath := qcr.GetCustomCrdsPath()
if crdPath == "" {
return "", nil
}
qInitByte, err := ExecuteKustomizeBuild(crdPath)
if err != nil {
fmt.Println("cannot generate custom crds", err)
return "", err
}
return string(qInitByte), nil
}
func (q *Qliksense) CheckAllCrdsInstalled() (bool, error) {
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
return false, err
}
customResourceDefinitionInterface, err := getCustomResourceDefinitionInterface()
if err != nil {
return false, err
}
if engineCRDs, err := getQliksenseInitCrds(qcr); err != nil {
return false, err
} else if allInstalled, err := checkCrdsInstalled(engineCRDs, customResourceDefinitionInterface); err != nil {
return false, err
} else if !allInstalled {
return false, nil
}
if customCrds, err := getCustomCrds(qcr); err != nil {
return false, err
} else if allInstalled, err := checkCrdsInstalled(customCrds, customResourceDefinitionInterface); err != nil {
return false, err
} else if !allInstalled {
return false, nil
}
if allInstalled, err := checkCrdsInstalled(q.GetOperatorCRDString(), customResourceDefinitionInterface); err != nil {
return false, err
} else if !allInstalled {
return false, nil
}
return true, nil
}
func checkCrdsInstalled(crds string, customResourceDefinitionInterface apixv1beta1client.CustomResourceDefinitionInterface) (bool, error) {
kuzResourceFactory := resmap.NewFactory(resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl()), nil)
if kuzResMap, err := kuzResourceFactory.NewResMapFromBytes([]byte(crds)); err != nil {
return false, err
} else {
for _, kuzRes := range kuzResMap.Resources() {
if customResourceDefinition, err := customResourceDefinitionInterface.Get(kuzRes.GetName(), v1.GetOptions{}); err != nil && apierrors.IsNotFound(err) {
return false, nil
} else if err != nil {
return false, err
} else if customResourceDefinition == nil {
return false, fmt.Errorf("failed looking up crd: %v", kuzRes.GetName())
}
}
return true, nil
}
}
func getCustomResourceDefinitionInterface() (apixv1beta1client.CustomResourceDefinitionInterface, error) {
homeDir, err := homedir.Dir()
if err != nil {
return nil, err
}
kubeconfigPath := filepath.Join(homeDir, ".kube", "config")
k8sRestConfig, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
if err != nil {
return nil, err
}
apixClient, err := apixv1beta1client.NewForConfig(k8sRestConfig)
if err != nil {
return nil, err
}
return apixClient.CustomResourceDefinitions(), nil
}

View File

@@ -1,135 +0,0 @@
package qliksense
import (
"io/ioutil"
"os"
"testing"
apixv1beta1client "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
"github.com/gobuffalo/packr/v2"
kapi_config "github.com/qlik-oss/k-apis/pkg/config"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
)
func TestGetQliksenseInitCrd(t *testing.T) {
someTmpRepoPath, err := DownloadFromGitRepoToTmpDir(defaultConfigRepoGitUrl, "master")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
crdFromContextConfig, err := getQliksenseInitCrds(&qapi.QliksenseCR{
KApiCr: kapi_config.KApiCr{
Spec: &kapi_config.CRSpec{
ManifestsRoot: someTmpRepoPath,
},
},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
crdFromDownloadedConfig, err := getQliksenseInitCrds(&qapi.QliksenseCR{
KApiCr: kapi_config.KApiCr{
Spec: &kapi_config.CRSpec{
ManifestsRoot: "",
},
},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if crdFromContextConfig != crdFromDownloadedConfig {
t.Fatalf("expected %v to equal %v, but they didn't", crdFromContextConfig, crdFromDownloadedConfig)
}
}
func TestCheckAllCrdsInstalled(t *testing.T) {
t.Skip("Skipping this test because it makes kubernetes calls")
tmpQlikSenseHome, err := ioutil.TempDir("", "tmp-qlik-sense-home-")
if err != nil {
t.Fatalf("unexpected error creating tmp dir: %v", err)
}
defer os.RemoveAll(tmpQlikSenseHome)
setupQliksenseTestDefaultContext(t, tmpQlikSenseHome, `
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
spec:
profile: docker-desktop
`)
q := &Qliksense{
QliksenseHome: tmpQlikSenseHome,
CrdBox: packr.New("crds", "./crds"),
}
if err := q.FetchQK8s("v1.50.3"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if allInstalled, err := q.CheckAllCrdsInstalled(); err != nil {
t.Fatalf("unexpected error: %v", err)
} else if allInstalled {
t.Fatal("expected crds to NOT be installed at this point")
}
if err := q.InstallCrds(&CrdCommandOptions{All: true}); err != nil {
t.Fatalf("unexpected error: %v", err)
} else if allInstalled, err := q.CheckAllCrdsInstalled(); err != nil {
t.Fatalf("unexpected error: %v", err)
} else if !allInstalled {
t.Fatal("expected crds to BE installed at this point")
}
//cleanup:
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
customResourceDefinitionInterface, err := getCustomResourceDefinitionInterface()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if engineCRDs, err := getQliksenseInitCrds(qcr); err != nil {
t.Fatalf("unexpected error: %v", err)
} else if err := deleteCrds(engineCRDs, customResourceDefinitionInterface); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if customCrd, err := getCustomCrds(qcr); err != nil {
t.Fatalf("unexpected error: %v", err)
} else if err := deleteCrds(customCrd, customResourceDefinitionInterface); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := deleteCrds(q.GetOperatorCRDString(), customResourceDefinitionInterface); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func deleteCrds(crds string, customResourceDefinitionInterface apixv1beta1client.CustomResourceDefinitionInterface) error {
kuzResourceFactory := resmap.NewFactory(resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl()), nil)
if kuzResMap, err := kuzResourceFactory.NewResMapFromBytes([]byte(crds)); err != nil {
return err
} else {
for _, kuzRes := range kuzResMap.Resources() {
if err := customResourceDefinitionInterface.Delete(kuzRes.GetName(), &v1.DeleteOptions{}); err != nil {
return err
}
}
return nil
}
}

View File

@@ -1,346 +1,253 @@
package qliksense
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/containers/image/v5/copy"
"github.com/containers/image/v5/signature"
"github.com/containers/image/v5/transports/alltransports"
imageTypes "github.com/containers/image/v5/types"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
"golang.org/x/net/context"
"gopkg.in/yaml.v2"
)
type imageNameParts struct {
name string
tag string
}
const (
imagesDirName = "images"
imageIndexDirName = "index"
imageSharedBlobsDirName = "blobs"
)
func (q *Qliksense) PullImages(version, profile string) error {
qConfig := qapi.NewQConfig(q.QliksenseHome)
if version != "" {
if !qConfig.IsRepoExistForCurrent(version) {
if err := q.FetchQK8s(version); err != nil {
return err
}
}
}
qcr, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
if !qcr.IsRepoExist() {
return errors.New("ManifestsRoot not found")
}
if profile != "" {
qcr.Spec.Profile = profile
if err := qConfig.WriteCR(qcr); err != nil {
return err
}
}
return q.PullImagesForCurrentCR()
}
// PullImages ...
func (q *Qliksense) PullImagesForCurrentCR() error {
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
version := qcr.GetLabelFromCr("version")
profile := qcr.Spec.Profile
repoDir := qcr.Spec.ManifestsRoot
imagesDir, err := setupImagesDir(q.QliksenseHome)
if err != nil {
return err
}
versionOut, stored, err := q.readOrGenerateVersionOutput(imagesDir, version, repoDir, profile)
if err != nil {
return err
}
images := versionOut.Images
if err := q.appendAdditionalImages(&images, qcr); err != nil {
return err
}
for _, image := range images {
if err := pullImage(image, imagesDir); err != nil {
fmt.Printf("%v\n", err)
return err
}
fmt.Print("---\n")
}
if version != "" && !stored {
if err := q.writeVersionOutput(versionOut, imagesDir, version); err != nil {
return err
}
}
return nil
}
func (q *Qliksense) appendOpsRunnerImage(images *[]string, qcr *qapi.QliksenseCR) {
if qcr.Spec.OpsRunner != nil && qcr.Spec.OpsRunner.Image != "" {
*images = append(*images, qcr.Spec.OpsRunner.Image)
}
}
func (q *Qliksense) appendPreflightImages(images *[]string) {
pf := qapi.NewPreflightConfig(q.QliksenseHome)
for _, preflightImage := range pf.GetImageMap() {
*images = append(*images, preflightImage)
}
}
func (q *Qliksense) appendOperatorImages(images *[]string) error {
if operatorImages, err := getImageList([]byte(q.GetOperatorControllerString())); err != nil {
return err
} else {
*images = append(*images, operatorImages...)
return nil
}
}
func pullImage(image, imagesDir string) error {
srcRef, err := alltransports.ParseImageName(fmt.Sprintf("docker://%v", image))
if err != nil {
return err
}
nameTag := getImageNameParts(image)
targetDir := filepath.Join(imagesDir, imageIndexDirName, nameTag.name, nameTag.tag)
if err := os.MkdirAll(targetDir, os.ModePerm); err != nil {
return err
}
destRef, err := alltransports.ParseImageName(fmt.Sprintf("oci:%v", targetDir))
if err != nil {
return err
}
policyContext, err := signature.NewPolicyContext(&signature.Policy{Default: []signature.PolicyRequirement{signature.NewPRInsecureAcceptAnything()}})
if err != nil {
return err
}
defer policyContext.Destroy()
fmt.Printf("==> Pulling image from %v\n", srcRef.StringWithinTransport())
if _, err := copy.Image(context.Background(), policyContext, destRef, srcRef, &copy.Options{
ReportWriter: os.Stdout,
SourceCtx: &imageTypes.SystemContext{
ArchitectureChoice: "amd64",
OSChoice: "linux",
},
DestinationCtx: &imageTypes.SystemContext{
OCISharedBlobDirPath: filepath.Join(imagesDir, imageSharedBlobsDirName),
},
}); err != nil {
return err
}
return nil
}
func (q *Qliksense) PushImagesForCurrentCR() error {
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
version := qcr.GetLabelFromCr("version")
profile := qcr.Spec.Profile
repoDir := qcr.Spec.ManifestsRoot
dockerConfigJsonSecret, err := qConfig.GetPushDockerConfigJsonSecret()
if err != nil {
if os.IsNotExist(err) {
dockerConfigJsonSecret = &qapi.DockerConfigJsonSecret{
Uri: qcr.Spec.GetImageRegistry(),
}
} else {
return err
}
}
imagesDir, err := setupImagesDir(q.QliksenseHome)
if err != nil {
return err
}
versionOut, stored, err := q.readOrGenerateVersionOutput(imagesDir, version, repoDir, profile)
if err != nil {
return err
}
images := versionOut.Images
if err := q.appendAdditionalImages(&images, qcr); err != nil {
return err
}
for _, image := range images {
if err = pushImage(image, imagesDir, dockerConfigJsonSecret); err != nil {
fmt.Printf("%v\n", err)
return err
}
fmt.Print("---\n")
}
if version != "" && !stored {
if err := q.writeVersionOutput(versionOut, imagesDir, version); err != nil {
return err
}
}
return nil
}
func (q *Qliksense) appendAdditionalImages(images *[]string, qcr *qapi.QliksenseCR) error {
if err := q.appendOperatorImages(images); err != nil {
return err
}
q.appendOpsRunnerImage(images, qcr)
q.appendPreflightImages(images)
return nil
}
func pushImage(image, imagesDir string, dockerConfigJsonSecret *qapi.DockerConfigJsonSecret) error {
imageNameParts := getImageNameParts(image)
srcDir := filepath.Join(imagesDir, imageIndexDirName, imageNameParts.name, imageNameParts.tag)
if exists, err := directoryExists(srcDir); err != nil {
return err
} else if !exists {
if err := pullImage(image, imagesDir); err != nil {
return err
}
}
srcRef, err := alltransports.ParseImageName(fmt.Sprintf("oci:%v", srcDir))
if err != nil {
return err
}
newImage := fmt.Sprintf("%v/%v:%v", dockerConfigJsonSecret.Uri, imageNameParts.name, imageNameParts.tag)
destRef, err := alltransports.ParseImageName(fmt.Sprintf("docker://%v", newImage))
if err != nil {
return err
}
policyContext, err := signature.NewPolicyContext(&signature.Policy{Default: []signature.PolicyRequirement{signature.NewPRInsecureAcceptAnything()}})
if err != nil {
return err
}
defer policyContext.Destroy()
destinationCtx := &imageTypes.SystemContext{
DockerInsecureSkipTLSVerify: imageTypes.OptionalBoolTrue,
}
if dockerConfigJsonSecret.Username != "" {
destinationCtx.DockerAuthConfig = &imageTypes.DockerAuthConfig{
Username: dockerConfigJsonSecret.Username,
Password: dockerConfigJsonSecret.Password,
}
}
fmt.Printf("==> Pushing image to: %v\n", destRef.StringWithinTransport())
if _, err = copy.Image(context.Background(), policyContext, destRef, srcRef, &copy.Options{
ReportWriter: os.Stdout,
SourceCtx: &imageTypes.SystemContext{
OCISharedBlobDirPath: filepath.Join(imagesDir, imageSharedBlobsDirName),
},
DestinationCtx: destinationCtx,
}); err != nil {
return err
}
return nil
}
func directoryExists(path string) (exists bool, err error) {
if info, err := os.Stat(path); err != nil && os.IsNotExist(err) {
exists = false
err = nil
} else if err != nil && !os.IsNotExist(err) {
exists = false
} else if err == nil && info.IsDir() {
exists = true
} else if err == nil && !info.IsDir() {
exists = false
err = fmt.Errorf("path: %v is occupied by a file instead of a directory", path)
}
return exists, err
}
func getImageNameParts(image string) imageNameParts {
segments := strings.Split(image, "/")
nameTag := strings.Split(segments[len(segments)-1], ":")
if len(nameTag) < 2 {
nameTag = append(nameTag, "latest")
}
return imageNameParts{
name: nameTag[0],
tag: nameTag[1],
}
}
func setupImagesDir(qliksenseHome string) (string, error) {
imagesDir := filepath.Join(qliksenseHome, imagesDirName)
imageIndexDir := filepath.Join(imagesDir, imageIndexDirName)
if err := os.MkdirAll(imageIndexDir, os.ModePerm); err != nil {
return "", err
}
sharedBlobsDir := filepath.Join(imagesDir, imageSharedBlobsDirName)
if err := os.MkdirAll(sharedBlobsDir, os.ModePerm); err != nil {
return "", err
}
return imagesDir, nil
}
func (q *Qliksense) readOrGenerateVersionOutput(imagesDir, version, repoDir, profile string) (versionOut *VersionOutput, stored bool, err error) {
if version != "" {
versionOut, err = q.readVersionOutput(imagesDir, version)
if versionOut != nil {
stored = true
}
}
if versionOut == nil {
if versionOut, err = q.AboutDir(repoDir, profile); err != nil {
return nil, false, err
}
}
return versionOut, stored, nil
}
func (q *Qliksense) readVersionOutput(imagesDir, version string) (*VersionOutput, error) {
var versionOut VersionOutput
versionFile := filepath.Join(imagesDir, version)
if versionOutBytes, err := ioutil.ReadFile(versionFile); err != nil {
return nil, err
} else if err = yaml.Unmarshal(versionOutBytes, &versionOut); err != nil {
return nil, err
}
return &versionOut, nil
}
func (q *Qliksense) writeVersionOutput(versionOut *VersionOutput, imagesDir, version string) error {
versionFile := filepath.Join(imagesDir, version)
if versionOutBytes, err := yaml.Marshal(versionOut); err != nil {
return err
} else if err = ioutil.WriteFile(versionFile, versionOutBytes, os.ModePerm); err != nil {
return err
}
return nil
}
package qliksense
import (
"fmt"
"io"
"io/ioutil"
"os"
"github.com/docker/cli/cli/command"
cliflags "github.com/docker/cli/cli/flags"
"github.com/docker/distribution/reference"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/term"
"github.com/docker/docker/registry"
"strings"
"golang.org/x/net/context"
yaml "gopkg.in/yaml.v2"
)
// Images ...
type Images struct {
Images []string `yaml:"images"`
}
// PullImages ...
func (p *Qliksense) PullImages(args []string) error {
var (
image string
err error
yamlVersion string
valid bool
images Images
)
println("getting images list...")
if yamlVersion, err = p.CallPorter(append([]string{"invoke", "--action", "about"}, args...),
func(x string) (out *string) {
if strings.HasPrefix(x, "qlikSenseVersion") {
valid = true
}
if strings.HasPrefix(x, "execution") {
valid = false
}
if valid {
return &x
}
return nil
}); err != nil {
return err
}
if err = yaml.Unmarshal([]byte(yamlVersion), &images); err != nil {
return err
}
for _, image = range images.Images {
if err = p.PullImage(image); err != nil {
fmt.Print(err)
}
println("---")
}
return nil
}
// PullImage ...
func (p *Qliksense) PullImage(imageName string) error {
var (
cli *command.DockerCli
dockerOutput io.Writer
response io.ReadCloser
pullOptions types.ImagePullOptions
ctx context.Context
ref reference.Named
repoInfo *registry.RepositoryInfo
authConfig types.AuthConfig
encodedAuth string
termFd uintptr
err error
)
// TODO: Create a real cli config context
ctx = context.Background()
if cli, err = command.NewDockerCli(); err != nil {
return err
}
if err = cli.Initialize(cliflags.NewClientOptions()); err != nil {
return err
}
if ref, err = reference.ParseNormalizedNamed(imageName); err != nil {
return err
}
if repoInfo, err = registry.ParseRepositoryInfo(ref); err != nil {
return err
}
authConfig = command.ResolveAuthConfig(ctx, cli, repoInfo.Index)
if encodedAuth, err = command.EncodeAuthToBase64(authConfig); err != nil {
return err
}
pullOptions = types.ImagePullOptions{
RegistryAuth: encodedAuth,
}
if response, err = cli.Client().ImagePull(ctx, imageName, pullOptions); err != nil {
return err
}
defer response.Close()
dockerOutput = ioutil.Discard
// if b.IsVerbose() {
// dockerOutput = b.Out
// }
dockerOutput = os.Stdout
termFd, _ = term.GetFdInfo(dockerOutput)
// Setting this to false here because Moby os.Exit(1) all over the place and this fails on WSL (only)
// when Term is true.
isTerm := false
if err = jsonmessage.DisplayJSONMessagesStream(response, dockerOutput, termFd, isTerm, nil); err != nil {
return err
}
return nil
}
// PullImage ...
func (p *Qliksense) TagAndPushImages(registry string) error {
var (
image string
err error
yamlVersion string
valid bool
images Images
)
if yamlVersion, err = p.CallPorter([]string{"invoke", "--action", "about"},
func(x string) (out *string) {
if strings.HasPrefix(x, "qlikSenseVersion") {
valid = true
}
if strings.HasPrefix(x, "execution") {
valid = false
}
if valid {
return &x
}
return nil
}); err != nil {
return err
}
if err = yaml.Unmarshal([]byte(yamlVersion), &images); err != nil {
return err
}
for _, image = range images.Images {
if err = p.TagAndPush(image, registry); err != nil {
fmt.Print(err)
}
println("---")
}
return nil
}
// PullImage ...
func (p *Qliksense) TagAndPush(image string, registryName string) error {
var (
cli *command.DockerCli
dockerOutput io.Writer
response io.ReadCloser
pushOptions types.ImagePushOptions
ctx context.Context
newName string
segments []string
imageList []types.ImageSummary
imageListOptions types.ImageListOptions
filterArgs filters.Args
ref reference.Named
repoInfo *registry.RepositoryInfo
authConfig types.AuthConfig
encodedAuth string
termFd uintptr
err error
)
// TODO: Create a real cli config context
ctx = context.Background()
if cli, err = command.NewDockerCli(); err != nil {
return err
}
if err = cli.Initialize(cliflags.NewClientOptions()); err != nil {
return err
}
segments = strings.Split(image, "/")
if segments[0] == "docker.io" {
image = strings.Join(segments[1:], "/")
}
newName = registryName + "/" + segments[len(segments)-1]
filterArgs = filters.NewArgs()
filterArgs.Add("reference", image)
imageListOptions = types.ImageListOptions{
Filters: filterArgs,
}
if imageList, err = cli.Client().ImageList(ctx, imageListOptions); err != nil {
return err
}
if imageList == nil || len(imageList) <= 0 {
fmt.Printf("Use `qliksense pull`, to pull %v for an air gap push", newName)
return nil
}
if err = cli.Client().ImageTag(ctx, image, newName); err != nil {
return err
}
if ref, err = reference.ParseNormalizedNamed(image); err != nil {
return err
}
if repoInfo, err = registry.ParseRepositoryInfo(ref); err != nil {
return err
}
authConfig = command.ResolveAuthConfig(ctx, cli, repoInfo.Index)
if encodedAuth, err = command.EncodeAuthToBase64(authConfig); err != nil {
return err
}
pushOptions = types.ImagePushOptions{
All: true,
RegistryAuth: encodedAuth,
}
if response, err = cli.Client().ImagePush(ctx, newName, pushOptions); err != nil {
return err
}
defer response.Close()
dockerOutput = ioutil.Discard
// if b.IsVerbose() {
// dockerOutput = b.Out
// }
dockerOutput = os.Stdout
termFd, _ = term.GetFdInfo(dockerOutput)
// Setting this to false here because Moby os.Exit(1) all over the place and this fails on WSL (only)
// when Term is true.
isTerm := false
if err = jsonmessage.DisplayJSONMessagesStream(response, dockerOutput, termFd, isTerm, nil); err != nil {
return err
}
return nil
}

View File

@@ -1,617 +0,0 @@
package qliksense
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io"
"io/ioutil"
"math/big"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/gobuffalo/packr/v2"
"github.com/containers/image/v5/copy"
"github.com/containers/image/v5/signature"
"github.com/containers/image/v5/transports/alltransports"
imageTypes "github.com/containers/image/v5/types"
"golang.org/x/net/context"
"github.com/qlik-oss/sense-installer/pkg/api"
"gopkg.in/yaml.v2"
)
func Test_locateDockerRegistryBinary(t *testing.T) {
binary, err := locateDockerRegistryBinary()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
cmd := exec.Command(binary, "--version")
out, err := cmd.Output()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
t.Logf("output: %v\n", string(out))
}
func Test_getSelfSignedCertAndKey(t *testing.T) {
host := "andriy.registry.com"
validity := time.Hour * 24 * 365
selfSignedCert, key, err := getSelfSignedCertAndKey(host, validity)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
fmt.Print(string(selfSignedCert))
fmt.Print(string(key))
}
type clientAuthType byte
const (
clientAuthNotProvided clientAuthType = iota
clientAuthProvided
clientAuthProvidedButIncorrect
)
func Test_Pull_Push_ImagesForCurrentCR(t *testing.T) {
if testing.Short() {
t.Skip("Skipping pull/push tests in short mode")
}
var testCases = []struct {
name string
registryAuth bool
clientAuth clientAuthType
expectPushSuccess bool
}{
{
name: "registry does not require auth and we do not provide auth",
registryAuth: false,
clientAuth: clientAuthNotProvided,
expectPushSuccess: true,
},
{
name: "registry does not require auth but we provide auth",
registryAuth: false,
clientAuth: clientAuthProvided,
expectPushSuccess: true,
},
{
name: "registry requires auth but we do not provide auth",
registryAuth: true,
clientAuth: clientAuthNotProvided,
expectPushSuccess: false,
},
{
name: "registry requires auth but we provide wrong auth",
registryAuth: true,
clientAuth: clientAuthProvidedButIncorrect,
expectPushSuccess: false,
},
{
name: "registry requires auth and we provide auth",
registryAuth: true,
clientAuth: clientAuthProvided,
expectPushSuccess: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
registryURI := "127.0.0.1:5555"
registry, err := setupRegistryV2At(registryURI, testCase.registryAuth)
if registry != nil {
defer func() {
registry.Close()
//fmt.Printf("registry stdout:\n%v\n", registry.stdOutBuffer.String())
//fmt.Printf("registry stderr:\n%v\n", registry.stdErrBuffer.String())
}()
}
if err != nil {
t.Fatalf("unexpected error setting up local registry: %v", err)
}
tmpQlikSenseHome, err := ioutil.TempDir("", "tmp-qlik-sense-home-")
if err != nil {
t.Fatalf("unexpected error creating tmp dir: %v", err)
}
defer os.RemoveAll(tmpQlikSenseHome)
if err := setupQlikSenseHome(t, tmpQlikSenseHome, registry, testCase.clientAuth); err != nil {
t.Fatalf("unexpected error setting up qliksense home: %v", err)
}
q := &Qliksense{
QliksenseHome: tmpQlikSenseHome,
CrdBox: &packr.Box{},
}
var versionOut VersionOutput
if err := q.PullImagesForCurrentCR(); err != nil {
t.Fatalf("unexpected pull error: %v", err)
} else if versionOutBytes, err := ioutil.ReadFile(path.Join(tmpQlikSenseHome, "images", "foo")); err != nil {
t.Fatalf("unexpected error reading version file: %v", err)
} else if err = yaml.Unmarshal(versionOutBytes, &versionOut); err != nil {
t.Fatalf("unexpected error unmarshalling version file: %v", err)
} else if len(versionOut.Images) != 1 || versionOut.Images[0] != "alpine:latest" {
t.Fatal(`did not find "alpine:latest"" in the version file`)
} else if infos, err := ioutil.ReadDir(path.Join(tmpQlikSenseHome, "images", "index", "alpine", "latest")); err != nil || len(infos) == 0 {
t.Fatal("expected images/index/alpine/latest directory to be non-empty")
} else if blobInfos, err := ioutil.ReadDir(path.Join(tmpQlikSenseHome, "images", "blobs", "sha256")); err != nil || len(blobInfos) == 0 {
t.Fatal("expected images/blobs/sha256 directory to be non-empty")
}
if testCase.expectPushSuccess {
if err := q.PushImagesForCurrentCR(); err != nil {
t.Fatalf("unexpected push error: %v", err)
} else if tmpImagesDir, err := ioutil.TempDir("", "tmp-images-"); err != nil {
t.Fatalf("unexpected error creating tmp dir: %v", err)
} else if err := testPullImage(fmt.Sprintf("%s/alpine:latest", registryURI), tmpImagesDir, registry); err != nil {
t.Fatalf("unexpected error pulling alpine:latest from the local registry: %v", err)
} else if infos, err := ioutil.ReadDir(path.Join(tmpImagesDir, "index", "alpine", "latest")); err != nil || len(infos) == 0 {
t.Fatal("expected index/alpine/latest directory to be non-empty")
} else if blobInfos, err := ioutil.ReadDir(path.Join(tmpImagesDir, "blobs", "sha256")); err != nil || len(blobInfos) == 0 {
t.Fatal("expected blobs/sha256 directory to be non-empty")
}
} else {
if err := q.PushImagesForCurrentCR(); err == nil {
t.Fatal("unexpected push success")
}
}
})
}
}
func Test_appendAdditionalImages(t *testing.T) {
tmpQlikSenseHome, err := ioutil.TempDir("", "tmp-qlik-sense-home-")
if err != nil {
t.Fatalf("unexpected error creating tmp dir: %v", err)
}
defer os.RemoveAll(tmpQlikSenseHome)
setupQliksenseTestDefaultContext(t, tmpQlikSenseHome, `
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
spec:
opsRunner:
image: some-gitops-image
`)
q := &Qliksense{
QliksenseHome: tmpQlikSenseHome,
CrdBox: packr.New("crds", "./crds"),
}
pf := api.NewPreflightConfig(q.QliksenseHome)
if err := pf.Initialize(); err != nil {
t.Fatalf("unexpected error initializing preflight: %v", err)
}
qConfig := api.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
t.Fatalf("unexpected error getting current CR: %v", err)
}
images := make([]string, 0)
if err := q.appendAdditionalImages(&images, qcr); err != nil {
t.Fatalf("unexpected error appending additional images: %v", err)
}
expectedNumberAdditionalImages := 5
if len(images) != expectedNumberAdditionalImages {
t.Fatalf("unexpected number of additional images: %v, expected: %v", len(images), expectedNumberAdditionalImages)
}
haveMatchingImage := func(test func(string) bool) bool {
for _, image := range images {
if test(image) {
return true
}
}
return false
}
if !haveMatchingImage(func(image string) bool {
return strings.Contains(image, "qlik-docker-oss.bintray.io/qliksense-operator:")
}) {
t.Fatal("expected to find the operator image in the list, but it wasn't there")
}
if !haveMatchingImage(func(image string) bool {
return image == "some-gitops-image"
}) {
t.Fatal("expected to find the GitOps image in the list, but it wasn't there")
}
if !haveMatchingImage(func(image string) bool {
return image == "nginx"
}) {
t.Fatal("expected to find the nginx Preflight image in the list, but it wasn't there")
}
if !haveMatchingImage(func(image string) bool {
return image == "subfuzion/netcat"
}) {
t.Fatal("expected to find the netcat Preflight image in the list, but it wasn't there")
}
if !haveMatchingImage(func(image string) bool {
return image == "qlik-docker-oss.bintray.io/preflight-mongo"
}) {
t.Fatal("expected to find the preflight-mongo image in the list, but it wasn't there")
}
}
func setupQlikSenseHome(t *testing.T, tmpQlikSenseHome string, registry *testRegistryV2, clientAuth clientAuthType) error {
version := "foo"
manifestsRootDir := filepath.ToSlash(path.Join(tmpQlikSenseHome, "contexts", "qlik-default", "repo", version))
cr := fmt.Sprintf(`
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
labels:
version: %s
spec:
profile: docker-desktop
configs:
qliksense:
- name: imageRegistry
value: %s
manifestsRoot: %s
rotateKeys: "yes"
releaseName: qlik-default
`, version, registry.url, manifestsRootDir)
setupQliksenseTestDefaultContext(t, tmpQlikSenseHome, cr)
if clientAuth == clientAuthProvided || clientAuth == clientAuthProvidedButIncorrect {
if registry.username == "" || clientAuth == clientAuthProvidedButIncorrect {
registry.username = "bad"
}
if registry.password == "" || clientAuth == clientAuthProvidedButIncorrect {
registry.password = "worse"
}
qConfig := api.NewQConfig(tmpQlikSenseHome)
if err := qConfig.SetPushDockerConfigJsonSecret(&api.DockerConfigJsonSecret{
Uri: registry.url,
Username: registry.username,
Password: registry.password,
}); err != nil {
return err
}
}
profileDir := path.Join(manifestsRootDir, "manifests", "docker-desktop")
if err := os.MkdirAll(profileDir, os.ModePerm); err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(profileDir, "kustomization.yaml"), []byte(`
resources:
- deployment.yaml
`), os.ModePerm); err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(profileDir, "deployment.yaml"), []byte(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: the-deployment
spec:
template:
spec:
containers:
- name: the-container
image: alpine:latest
`), os.ModePerm); err != nil {
return err
}
transformersDir := path.Join(manifestsRootDir, "transformers")
if err := os.MkdirAll(transformersDir, os.ModePerm); err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(transformersDir, "qseokversion.yaml"), []byte(`
apiVersion: qlik.com/v1
kind: SelectivePatch
metadata:
name: qseokversion
enabled: true
patches:
- target:
kind: HelmChart
labelSelector: name!=qliksense-init
patch: |-
chartName: qliksense
chartVersion: 1.21.23
`), os.ModePerm); err != nil {
return err
}
return nil
}
type testRegistryV2 struct {
cmd *exec.Cmd
url string
dir string
username string
password string
email string
stdOutBuffer *bytes.Buffer
stdErrBuffer *bytes.Buffer
}
func locateDockerRegistryBinary() (string, error) {
if exePath, err := exec.LookPath("docker-registry"); err != nil {
if cwd, err := os.Getwd(); err != nil {
return "", err
} else {
return path.Join(cwd, "docker-registry"), nil
}
} else {
return exePath, nil
}
}
func setupRegistryV2At(url string, auth bool) (*testRegistryV2, error) {
reg, err := newTestRegistryV2At(url, auth)
if err != nil {
return nil, err
}
// Wait for registry to be ready to serve requests.
for i := 0; i != 50; i++ {
if err := reg.Ping("http"); err == nil {
fmt.Print("registry http ping succeeded\n")
break
} else {
fmt.Printf("registry http ping error: %v\n", err)
}
if err := reg.Ping("https"); err == nil {
fmt.Print("registry https ping succeeded\n")
break
} else {
fmt.Printf("registry https ping error: %v\n", err)
}
time.Sleep(100 * time.Millisecond)
}
if err != nil {
return reg, errors.New("timeout waiting for test registry to become available")
}
return reg, nil
}
func newTestRegistryV2At(url string, auth bool) (*testRegistryV2, error) {
tmp, err := ioutil.TempDir("", "registry-test-")
if err != nil {
return nil, err
}
template := `version: 0.1
loglevel: info
storage:
filesystem:
rootdirectory: %s
delete:
enabled: true
http:
addr: %s
%s`
var (
htpasswd string
username string
password string
email string
)
var env []string
if auth {
if certificate, key, err := getSelfSignedCertAndKey("localhost", time.Hour*24); err != nil {
return nil, err
} else {
certPath := filepath.Join(tmp, "domain.crt")
if err := ioutil.WriteFile(certPath, certificate, os.FileMode(0644)); err != nil {
return nil, err
}
keyPath := filepath.Join(tmp, "domain.key")
if err := ioutil.WriteFile(keyPath, key, os.FileMode(0644)); err != nil {
return nil, err
}
env = append(env, fmt.Sprintf("REGISTRY_HTTP_TLS_CERTIFICATE=%v", certPath))
env = append(env, fmt.Sprintf("REGISTRY_HTTP_TLS_KEY=%v", keyPath))
}
htpasswdPath := filepath.Join(tmp, "htpasswd")
userpasswd := "testuser:$2y$05$sBsSqk0OpSD1uTZkHXc4FeJ0Z70wLQdAX/82UiHuQOKbNbBrzs63m"
username = "testuser"
password = "testpassword"
email = "test@test.org"
if err := ioutil.WriteFile(htpasswdPath, []byte(userpasswd), os.FileMode(0644)); err != nil {
return nil, err
}
htpasswd = fmt.Sprintf(`auth:
htpasswd:
realm: basic-realm
path: %s
`, htpasswdPath)
}
confPath := filepath.Join(tmp, "config.yaml")
config, err := os.Create(confPath)
if err != nil {
return nil, err
}
if _, err := fmt.Fprintf(config, template, tmp, url, htpasswd); err != nil {
os.RemoveAll(tmp)
return nil, err
}
dockerRegistryBinaryPath, err := locateDockerRegistryBinary()
if err != nil {
return nil, err
}
cmd := exec.Command(dockerRegistryBinaryPath, "serve", confPath)
cmd.Env = env
stdOutBuf, stdErrBuf, err := consumeAndLogOutputs(fmt.Sprintf("registry-%s", url), cmd)
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
os.RemoveAll(tmp)
return nil, err
}
return &testRegistryV2{
cmd: cmd,
url: url,
dir: tmp,
username: username,
password: password,
email: email,
stdOutBuffer: stdOutBuf,
stdErrBuffer: stdErrBuf,
}, nil
}
func (t *testRegistryV2) Ping(protocol string) error {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Get(fmt.Sprintf("%v://%s/v2/", protocol, t.url))
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusUnauthorized {
return fmt.Errorf("registry ping replied with an unexpected status code %d", resp.StatusCode)
}
return nil
}
func (t *testRegistryV2) Close() {
t.cmd.Process.Kill()
os.RemoveAll(t.dir)
}
func consumeAndLogOutputStream(id string, f io.ReadCloser) *bytes.Buffer {
buff := &bytes.Buffer{}
go func() {
defer func() {
f.Close()
fmt.Fprintf(buff, "[%s]: Closed\n", id)
}()
buf := make([]byte, 1024)
for {
fmt.Fprintf(buff, "[%s]: waiting\n", id)
n, err := f.Read(buf)
fmt.Fprintf(buff, "[%s]: got %d,%#v: %s\n", id, n, err, strings.TrimSuffix(string(buf[:n]), "\n"))
if n <= 0 {
break
}
}
}()
return buff
}
// consumeAndLogOutputs causes all output to stdout and stderr from an *exec.Cmd to be logged to c
func consumeAndLogOutputs(id string, cmd *exec.Cmd) (*bytes.Buffer, *bytes.Buffer, error) {
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, nil, err
}
return consumeAndLogOutputStream(id+" stdout", stdout), consumeAndLogOutputStream(id+" stderr", stderr), nil
}
func getSelfSignedCertAndKey(hostname string, validity time.Duration) (certificate, key []byte, err error) {
priv, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return nil, nil, err
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, fmt.Errorf("ailed to generate serial number: %s", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"self-signed"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(validity),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
DNSNames: []string{hostname},
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, nil, fmt.Errorf("failed to create certificate: %s", err)
}
certificate = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return nil, nil, fmt.Errorf("unable to marshal private key: %v", err)
}
key = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
return certificate, key, nil
}
func testPullImage(image, imagesDir string, registry *testRegistryV2) error {
srcRef, err := alltransports.ParseImageName(fmt.Sprintf("docker://%v", image))
if err != nil {
return err
}
nameTag := getImageNameParts(image)
targetDir := filepath.Join(imagesDir, imageIndexDirName, nameTag.name, nameTag.tag)
if err := os.MkdirAll(targetDir, os.ModePerm); err != nil {
return err
}
destRef, err := alltransports.ParseImageName(fmt.Sprintf("oci:%v", targetDir))
if err != nil {
return err
}
policyContext, err := signature.NewPolicyContext(&signature.Policy{Default: []signature.PolicyRequirement{signature.NewPRInsecureAcceptAnything()}})
if err != nil {
return err
}
defer policyContext.Destroy()
fmt.Printf("==> Test is pulling image from %v\n", srcRef.StringWithinTransport())
sourceCtx := &imageTypes.SystemContext{
ArchitectureChoice: "amd64",
OSChoice: "linux",
DockerInsecureSkipTLSVerify: imageTypes.OptionalBoolTrue,
}
if registry.username != "" {
sourceCtx.DockerAuthConfig = &imageTypes.DockerAuthConfig{
Username: registry.username,
Password: registry.password,
}
}
if _, err := copy.Image(context.Background(), policyContext, destRef, srcRef, &copy.Options{
ReportWriter: os.Stdout,
SourceCtx: sourceCtx,
DestinationCtx: &imageTypes.SystemContext{
OCISharedBlobDirPath: filepath.Join(imagesDir, imageSharedBlobsDirName),
},
}); err != nil {
return err
}
return nil
}

View File

@@ -1,157 +0,0 @@
package qliksense
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"
kapis_git "github.com/qlik-oss/k-apis/pkg/git"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
)
type FetchCommandOptions struct {
GitUrl string
AccessToken string
Version string
SecretName string
Overwrite bool
}
const (
QLIK_GIT_REPO = "https://github.com/qlik-oss/qliksense-k8s"
)
func (q *Qliksense) FetchQK8s(version string) error {
qConfig := qapi.NewQConfig(q.QliksenseHome)
return fetchAndUpdateCR(qConfig, version)
}
func (q *Qliksense) FetchK8sWithOpts(opts *FetchCommandOptions) error {
qConfig := qapi.NewQConfig(q.QliksenseHome)
cr, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
if opts.AccessToken != "" {
encKey, err := qConfig.GetEncryptionKeyFor(cr.GetName())
if err != nil {
return err
}
if err := cr.SetFetchAccessToken(opts.AccessToken, encKey); err != nil {
return err
}
}
if opts.SecretName != "" {
cr.SetFetchAccessSecretName(opts.SecretName)
}
if opts.GitUrl != "" {
cr.SetFetchUrl(opts.GitUrl)
}
v := getVersion(opts, cr)
if v != "" && qConfig.IsRepoExistForCurrent(v) {
if opts.Overwrite || getVerionsOverwriteConfirmation(v) == "y" {
if err := qConfig.DeleteRepoForCurrent(v); err != nil {
return err
}
} else {
// nothing to do
return nil
}
}
qConfig.WriteCR(cr)
return fetchAndUpdateCR(qConfig, v)
}
// fetchAndUpdateCR fetch
func fetchAndUpdateCR(qConfig *qapi.QliksenseConfig, version string) error {
qcr, err := qConfig.GetCurrentCR()
if err != nil {
fmt.Println("cannot get the current-context cr", err)
return err
}
if version == "" {
if qcr.GetLabelFromCr("version") == "" {
if encKey, err := qConfig.GetEncryptionKeyFor(qcr.GetName()); err != nil {
return err
} else if version, err = getLatestTag(qcr.GetFetchUrl(), qcr.GetFetchAccessToken(encKey)); err != nil {
return err
}
} else {
version = qcr.GetLabelFromCr("version")
}
}
encKey, err := qConfig.GetEncryptionKeyFor(qcr.GetName())
if err != nil {
return err
}
// downlaod to temp first
tempDest, err := fetchToTempDir(qcr.GetFetchUrl(), version, qcr.GetFetchAccessToken(encKey))
if err != nil {
return err
}
destDir := qConfig.BuildRepoPath(version)
fmt.Printf("fetching version [%s] from %s\n", version, qcr.GetFetchUrl())
if err := qapi.CopyDirectory(tempDest, destDir); err != nil {
return nil
}
qcr.Spec.ManifestsRoot = qConfig.BuildCurrentManifestsRoot(version)
qcr.AddLabelToCr("version", version)
return qConfig.WriteCurrentContextCR(qcr)
}
func fetchToTempDir(gitUrl, gitRef, accessToken string) (string, error) {
tmpDir, err := ioutil.TempDir("", "")
if err != nil {
return "", err
}
downloadPath := path.Join(tmpDir, "repo")
var auth transport.AuthMethod
if accessToken != "" {
auth = &http.BasicAuth{
Username: "something",
Password: accessToken,
}
}
if repo, err := kapis_git.CloneRepository(downloadPath, gitUrl, auth); err != nil {
return "", err
} else if err := kapis_git.Checkout(repo, gitRef, "", auth); err != nil {
return "", err
} else {
return downloadPath, nil
}
}
func getVersion(opts *FetchCommandOptions, qcr *qapi.QliksenseCR) string {
if opts.Version == "" {
if qcr.GetLabelFromCr("version") != "" {
return qcr.GetLabelFromCr("version")
}
}
return opts.Version
}
func getVerionsOverwriteConfirmation(version string) string {
reader := bufio.NewReader(os.Stdin)
fmt.Println("The version [" + version + "] already exist")
cfm := "n"
for {
fmt.Print("Do you want to delete and fetch again [y/N]: ")
cfm, _ = reader.ReadString('\n')
cfm = strings.Replace(cfm, "\n", "", -1)
cfm = strings.TrimSpace(cfm)
if cfm == "" {
cfm = "n"
}
cfm = strings.ToLower(cfm)
if cfm == "y" || cfm == "n" {
break
}
}
return cfm
}

View File

@@ -1,50 +0,0 @@
package qliksense
import (
"io/ioutil"
"path/filepath"
"testing"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
)
func TestFetchAndUpdateCR(t *testing.T) {
tempHome, _ := ioutil.TempDir("", "")
q := &Qliksense{
QliksenseHome: tempHome,
}
q.SetUpQliksenseContext("test1")
qConfig := qapi.NewQConfig(tempHome)
if err := fetchAndUpdateCR(qConfig, "v0.0.2"); err != nil {
t.Log(err)
t.FailNow()
}
actualCrFile := filepath.Join(tempHome, "contexts", "test1", "test1.yaml")
cr := &qapi.QliksenseCR{}
if err := qapi.ReadFromFile(cr, actualCrFile); err != nil {
t.Log(err)
t.FailNow()
}
if cr.Spec.ManifestsRoot != "contexts/test1/qlik-k8s/v0.0.2" {
t.Log("actual path: " + cr.Spec.ManifestsRoot + ", expected path: contexts/test1/qlik-k8s/v0.0.2")
t.FailNow()
}
//testing latest tag is fetched
cr.AddLabelToCr("version", "")
qConfig.WriteCR(cr)
err := fetchAndUpdateCR(qConfig, "")
if err != nil {
t.Log(err)
t.Fail()
}
cr = &qapi.QliksenseCR{}
qapi.ReadFromFile(cr, actualCrFile)
v := cr.GetLabelFromCr("version")
if v == "" || v == "v0.0.2" {
t.Log("should get latest but got version: " + v)
t.Fail()
}
}

View File

@@ -1,155 +0,0 @@
package qliksense
import (
"errors"
"fmt"
"github.com/Masterminds/semver/v3"
"github.com/qlik-oss/k-apis/pkg/git"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
)
type LsRemoteCmdOptions struct {
IncludeBranches bool
Limit int
}
func (q *Qliksense) GetInstallableVersions(opts *LsRemoteCmdOptions) error {
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
return err
}
var repoPath string
if qcr.Spec.GetManifestsRoot() != "" {
repoPath = qcr.Spec.GetManifestsRoot()
} else {
repoPath, err = DownloadFromGitRepoToTmpDir(defaultConfigRepoGitUrl, "master")
if err != nil {
return err
}
}
r, err := git.OpenRepository(repoPath)
if err != nil {
return err
}
remoteRefsList, err := git.GetRemoteRefs(r, nil,
&git.RemoteRefConstraints{
Include: true,
Sort: true,
SortOrder: git.RefSortOrderDescending,
},
&git.RemoteRefConstraints{
Include: opts.IncludeBranches,
Sort: true,
SortOrder: git.RefSortOrderAscending,
})
if err != nil {
return err
}
if len(remoteRefsList) < 1 {
return errors.New("cannot find git remote information in the config repository")
}
var originRemoteRefs *git.RemoteRefs
for _, remoteRefs := range remoteRefsList {
if remoteRefs.Name == "origin" {
originRemoteRefs = remoteRefs
break
}
}
if originRemoteRefs == nil {
return errors.New(`cannot find git remote called "origin" in the config repository`)
}
tags := originRemoteRefs.Tags
if len(tags) > opts.Limit {
tags = tags[:opts.Limit]
}
fmt.Print("Versions:\n")
for _, tag := range tags {
fmt.Printf(" %s\n", tag)
}
if opts.IncludeBranches {
branches := originRemoteRefs.Branches
if len(branches) > opts.Limit {
branches = branches[:opts.Limit]
}
fmt.Print("Branches:\n")
for _, branch := range branches {
fmt.Printf(" %s\n", branch)
}
}
return nil
}
func getLatestTag(repoUrl, accessToken string) (string, error) {
if repoUrl == "" {
return "", errors.New("repo url is empty")
}
repoPath, err := fetchToTempDir(repoUrl, "master", accessToken)
if err != nil {
return "", err
}
r, err := git.OpenRepository(repoPath)
if err != nil {
return "", err
}
remoteRefsList, err := git.GetRemoteRefs(r, nil,
&git.RemoteRefConstraints{
Include: true,
Sort: true,
SortOrder: git.RefSortOrderDescending,
},
&git.RemoteRefConstraints{
Include: false,
Sort: true,
SortOrder: git.RefSortOrderAscending,
})
if err != nil {
return "", err
}
if len(remoteRefsList) < 1 {
return "", errors.New("cannot find git remote information in the config repository")
}
var originRemoteRefs *git.RemoteRefs
for _, remoteRefs := range remoteRefsList {
if remoteRefs.Name == "origin" {
originRemoteRefs = remoteRefs
break
}
}
if originRemoteRefs == nil {
return "", errors.New(`cannot find git remote called "origin" in the config repository`)
}
tags := originRemoteRefs.Tags
if len(tags) == 0 {
return "", errors.New(("no tags exists in the repo: " + repoPath))
}
maxSem, _ := semver.NewVersion(tags[0])
for _, sv := range tags[1:] {
if sv == "" {
continue
}
v, err := semver.NewVersion(sv)
if err != nil {
// it may happen, in the repo some tags may not conform to semver
//fmt.Println("the tag is not conform to semver: " + sv)
continue
}
if maxSem == nil || maxSem.LessThan(v) {
maxSem = v
}
}
return maxSem.Original(), nil
}

View File

@@ -1,25 +0,0 @@
package qliksense
import (
"testing"
"github.com/Masterminds/semver/v3"
)
func TestGetLatestTag(t *testing.T) {
s, err := getLatestTag(defaultConfigRepoGitUrl, "")
if s == "" || err != nil {
t.Log(err)
t.Fail()
}
sv, err := semver.NewVersion(s)
if err != nil {
t.Log(err)
t.Log(sv)
}
baseV, _ := semver.NewVersion("v0.0.8")
if !sv.GreaterThan(baseV) {
t.Log("Expected greater than v0.0.8, but got: " + s)
t.Fail()
}
}

View File

@@ -1,228 +0,0 @@
package qliksense
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"github.com/mitchellh/go-homedir"
"github.com/qlik-oss/k-apis/pkg/config"
"github.com/qlik-oss/k-apis/pkg/cr"
"sigs.k8s.io/kustomize/api/filesys"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
)
type InstallCommandOptions struct {
StorageClass string
MongodbUri string
RotateKeys string
DryRun bool
}
func (q *Qliksense) InstallQK8s(version string, opts *InstallCommandOptions, keepPatchFiles bool) error {
// step1: fetch 1.0.0 # pull down qliksense-k8s@1.0.0
// step2: operator view | kubectl apply -f # operator manifest (CRD)
// step3: config apply | kubectl apply -f # generates patches (if required) in configuration directory, applies manifest
// step4: config view | kubectl apply -f # generates Custom Resource manifest (CR)
// fetch the version
qConfig := qapi.NewQConfig(q.QliksenseHome)
if !keepPatchFiles {
if err := q.DiscardAllUnstagedChangesFromGitRepo(qConfig); err != nil {
fmt.Printf("error removing temporary changes to the config: %v\n", err)
}
}
qcr, err := qConfig.GetCurrentCR()
if err != nil {
fmt.Println("cannot get the current-context cr", err)
return err
}
qcr.SetEULA("yes")
if opts.MongodbUri != "" {
qcr.Spec.AddToSecrets("qliksense", "mongodbUri", opts.MongodbUri, "")
}
if opts.StorageClass != "" {
qcr.Spec.StorageClassName = opts.StorageClass
}
if opts.RotateKeys != "" {
qcr.Spec.RotateKeys = opts.RotateKeys
}
// for debugging purpose
if opts.DryRun {
// generate patches
qcr.Spec.RotateKeys = "None"
userHomeDir, _ := homedir.Dir()
fmt.Println("Generating patches only")
cr.GeneratePatches(&qcr.KApiCr, path.Join(userHomeDir, ".kube", "config"))
return nil
}
qConfig.WriteCurrentContextCR(qcr)
if installed, err := q.CheckAllCrdsInstalled(); err != nil {
fmt.Println("error verifying whether CRDs are installed", err)
return err
} else if !installed {
return errors.New(`please install CRDs by executing: $ qliksense crds install`)
}
if err := applyImagePullSecret(qConfig); err != nil {
return err
}
//CRD will be installed outside of operator
//install operator controller into the namespace
fmt.Println("Installing operator controller")
if operatorControllerString, err := q.getProcessedOperatorControllerString(qcr); err != nil {
fmt.Println("error extracting/transforming operator controller", err)
return err
} else if err := qapi.KubectlApply(operatorControllerString, ""); err != nil {
fmt.Println("cannot do kubectl apply on operator controller", err)
return err
}
// create patch dependent resources
fmt.Println("Installing resources used by the kuztomize patch")
if err := q.createK8sResourceBeforePatch(qcr); err != nil {
return err
}
if qcr.Spec.OpsRunner != nil {
// fetching and applying manifest will be in the operator controller
// get decrypted cr
if dcr, err := qConfig.GetDecryptedCr(qcr); err != nil {
return err
} else {
return q.applyCR(dcr)
}
}
if !qcr.IsRepoExist() {
if err := fetchAndUpdateCR(qConfig, version); err != nil {
return err
}
}
qcr, err = qConfig.GetCurrentCR()
if err != nil {
fmt.Println("cannot get the current-context cr", err)
return err
} else if qcr.Spec.GetManifestsRoot() == "" {
return errors.New("cannot get the manifest root. Use qliksense fetch <version> or qliksense set manifestsRoot")
}
// install generated manifests into cluster
fmt.Println("Installing generated manifests into the cluster")
if dcr, err := qConfig.GetDecryptedCr(qcr); err != nil {
return err
} else {
if IsQliksenseInstalled(dcr.GetName()) {
return q.UpgradeQK8s(keepPatchFiles)
}
if err := q.applyConfigToK8s(dcr); err != nil {
fmt.Println("cannot do kubectl apply on manifests")
return err
} else {
return q.applyCR(dcr)
}
}
}
func (q *Qliksense) getProcessedOperatorControllerString(qcr *qapi.QliksenseCR) (string, error) {
operatorControllerString := q.GetOperatorControllerString()
if imageRegistry := qcr.Spec.GetImageRegistry(); imageRegistry != "" {
return kustomizeForImageRegistry(operatorControllerString, pullSecretName,
path.Join(qliksenseOperatorImageRepo, qliksenseOperatorImageName),
path.Join(imageRegistry, qliksenseOperatorImageName))
}
return operatorControllerString, nil
}
func applyImagePullSecret(qConfig *qapi.QliksenseConfig) error {
if pullDockerConfigJsonSecret, err := qConfig.GetPullDockerConfigJsonSecret(); err == nil {
if dockerConfigJsonSecretYaml, err := pullDockerConfigJsonSecret.ToYaml(""); err != nil {
return err
} else if err := qapi.KubectlApply(string(dockerConfigJsonSecretYaml), ""); err != nil {
return err
}
}
return nil
}
func kustomizeForImageRegistry(resources, dockerConfigJsonSecretName, name, newName string) (string, error) {
dir, err := ioutil.TempDir("", "")
if err != nil {
return "", err
}
defer os.RemoveAll(dir)
if err := ioutil.WriteFile(filepath.Join(dir, "resources.yaml"), []byte(resources), os.ModePerm); err != nil {
return "", err
} else if err := ioutil.WriteFile(filepath.Join(dir, "addImagePullSecrets.yaml"), []byte(fmt.Sprintf(`
apiVersion: builtin
kind: PatchTransformer
metadata:
name: notImportantHere
patch: '[{"op": "add", "path": "/spec/template/spec/imagePullSecrets", "value": [{"name": "%v"}]}]'
target:
name: .*-operator
kind: Deployment
`, dockerConfigJsonSecretName)), os.ModePerm); err != nil {
return "", err
} else if err := ioutil.WriteFile(filepath.Join(dir, "kustomization.yaml"), []byte(fmt.Sprintf(`
resources:
- resources.yaml
transformers:
- addImagePullSecrets.yaml
images:
- name: %s
newName: %s
`, name, newName)), os.ModePerm); err != nil {
return "", err
} else if out, err := executeKustomizeBuildForFileSystem(dir, filesys.MakeFsOnDisk()); err != nil {
return "", err
} else {
return string(out), nil
}
}
func (q *Qliksense) applyCR(cr *qapi.QliksenseCR) error {
// install operator cr into cluster
//get the current context cr
fmt.Println("Installing operator CR into the cluster")
r, err := cr.GetString()
if err != nil {
return err
}
if err := qapi.KubectlApply(r, ""); err != nil {
fmt.Println("cannot do kubectl apply on operator CR")
return err
}
return nil
}
func (q *Qliksense) createK8sResourceBeforePatch(qcr *qapi.QliksenseCR) error {
for svc, nvs := range qcr.Spec.Secrets {
for _, nv := range nvs {
if isK8sSecretNeedToCreate(nv) {
fmt.Println(filepath.Join(qcr.GetK8sSecretsFolder(q.QliksenseHome), svc+".yaml"))
if secS, err := q.PrepareK8sSecret(filepath.Join(qcr.GetK8sSecretsFolder(q.QliksenseHome), svc+".yaml")); err != nil {
return err
} else {
return qapi.KubectlApply(secS, "")
}
}
}
}
return nil
}
func isK8sSecretNeedToCreate(nv config.NameValue) bool {
return nv.ValueFrom != nil
}

View File

@@ -1,176 +0,0 @@
package qliksense
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"testing"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
"github.com/gobuffalo/packr/v2"
qapi "github.com/qlik-oss/sense-installer/pkg/api"
)
func TestCreateK8sResourceBeforePatch(t *testing.T) {
td := setup()
sampleCr := `
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-test3
labels:
version: v0.0.2
spec:
git:
repository: https://github.com/ffoysal/qliksense-k8s
accessToken: abababababababaab
userName: "blblbl"
gitOps:
enabled: "no"
schedule: "*/1 * * * *"
watchBranch: pr-branch-db1d26d6
image: qlik-docker-oss.bintray.io/qliksense-repo-watcher
configs:
qliksense:
- name: acceptEULA
value: "yes"
secrets:
qliksense:
- name: mongodbUri
value: mongodb://qlik-default-mongodb:27017/qliksense?ssl=false
profile: docker-desktop
rotateKeys: "yes"`
crFile := filepath.Join(testDir, "install_test.yaml")
ioutil.WriteFile(crFile, []byte(sampleCr), 0644)
q := New(testDir)
file, e := os.Open(crFile)
if e != nil {
t.Log(e)
t.FailNow()
}
if err := q.LoadCr(file, false); err != nil {
t.Log(err)
t.FailNow()
}
qConfig := qapi.NewQConfig(testDir)
cr, err := qConfig.GetCR("qlik-test3")
if err != nil {
t.Log(err)
t.FailNow()
}
if err = q.createK8sResourceBeforePatch(cr); err != nil {
t.Log(err)
t.FailNow()
}
td()
}
func setupQliksenseTestDefaultContext(t *testing.T, tmpQlikSenseHome, CR string) {
if err := ioutil.WriteFile(path.Join(tmpQlikSenseHome, "config.yaml"), []byte(`
apiVersion: config.qlik.com/v1
kind: QliksenseConfig
metadata:
name: QliksenseConfigMetadata
spec:
contexts:
- name: qlik-default
crFile: contexts/qlik-default/qlik-default.yaml
currentContext: qlik-default
`), os.ModePerm); err != nil {
t.Fatalf("unexpected error: %v", err)
}
defaultContextDir := path.Join(tmpQlikSenseHome, "contexts", "qlik-default")
if err := os.MkdirAll(defaultContextDir, os.ModePerm); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := ioutil.WriteFile(path.Join(defaultContextDir, "qlik-default.yaml"), []byte(CR), os.ModePerm); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func Test_getProcessedOperatorControllerString(t *testing.T) {
tmpQlikSenseHome, err := ioutil.TempDir("", "tmp-qlik-sense-home-")
if err != nil {
t.Fatalf("unexpected error creating tmp dir: %v", err)
}
defer os.RemoveAll(tmpQlikSenseHome)
registry := "registryFoo"
setupQliksenseTestDefaultContext(t, tmpQlikSenseHome, fmt.Sprintf(`
apiVersion: qlik.com/v1
kind: Qliksense
metadata:
name: qlik-default
spec:
configs:
qliksense:
- name: imageRegistry
value: %v
`, registry))
q := &Qliksense{
QliksenseHome: tmpQlikSenseHome,
CrdBox: packr.New("crds", "./crds"),
}
qConfig := qapi.NewQConfig(q.QliksenseHome)
qcr, err := qConfig.GetCurrentCR()
if err != nil {
t.Fatalf("unexpected error getting current CR: %v", err)
}
originalOperatorString := q.GetOperatorControllerString()
processedOperatorString, err := q.getProcessedOperatorControllerString(qcr)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
controllerImageChecks := map[string]func(t *testing.T, controllerImage string){
originalOperatorString: func(t *testing.T, controllerImage string) {
expectedControllerImagePrefix := fmt.Sprintf("%v/%v:", qliksenseOperatorImageRepo, qliksenseOperatorImageName)
if !strings.HasPrefix(controllerImage, expectedControllerImagePrefix) {
t.Fatalf("expected controller image: %v to have prefix: %v", controllerImage, expectedControllerImagePrefix)
}
},
processedOperatorString: func(t *testing.T, controllerImage string) {
expectedControllerImagePrefix := fmt.Sprintf("%v/%v:", registry, qliksenseOperatorImageName)
if !strings.HasPrefix(controllerImage, expectedControllerImagePrefix) {
t.Fatalf("expected controller image: %v to have prefix: %v", controllerImage, expectedControllerImagePrefix)
}
},
}
resourceFactory := resmap.NewFactory(resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl()), nil)
for operatorString, controllerImageCheck := range controllerImageChecks {
resMap, err := resourceFactory.NewResMapFromBytes([]byte(operatorString))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
res, err := resMap.GetById(resid.NewResId(resid.Gvk{
Group: "apps",
Version: "v1",
Kind: "Deployment",
}, "qliksense-operator"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
controllerImage, err := res.GetString("spec.template.spec.containers[0].image")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
controllerImageCheck(t, controllerImage)
}
}

Some files were not shown because too many files have changed in this diff Show More