You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by nf...@apache.org on 2020/10/21 07:40:04 UTC
[camel-k] 02/07: API: remove unnecessary packages
This is an automated email from the ASF dual-hosted git repository.
nferraro pushed a commit to branch api
in repository https://gitbox.apache.org/repos/asf/camel-k.git
commit f4d78bec691ce2f1303c80d5844d60a3f9042d98
Author: Nicola Ferraro <ni...@gmail.com>
AuthorDate: Thu Apr 30 17:46:50 2020 +0200
API: remove unnecessary packages
---
pkg/apis/addtoscheme_knative_eventing.go | 33 --
pkg/apis/addtoscheme_knative_serving.go | 27 --
pkg/apis/addtoscheme_monitoring.go | 25 --
pkg/apis/addtoscheme_olm.go | 29 --
pkg/apis/addtoscheme_openshift.go | 25 --
pkg/util/camel/camel_runtime.go | 50 ---
pkg/util/camel/camel_runtime_catalog.go | 123 -------
pkg/util/camel/camel_types.go | 50 ---
pkg/util/camel/camel_util.go | 96 -----
pkg/util/camel/camel_util_test.go | 73 ----
pkg/util/cancellable/cancellable.go | 51 ---
pkg/util/config/config.go | 18 -
pkg/util/controller/util.go | 45 ---
pkg/util/defaults/defaults.go | 45 ---
pkg/util/digest/digest.go | 193 ----------
pkg/util/envvar/envvar.go | 98 -----
pkg/util/envvar/envvar_test.go | 103 ------
pkg/util/gzip/compress.go | 93 -----
pkg/util/gzip/compress_test.go | 33 --
pkg/util/indentedwriter/writer.go | 74 ----
pkg/util/knative/apis.go | 225 ------------
pkg/util/knative/apis_test.go | 165 ---------
pkg/util/knative/enabled.go | 93 -----
pkg/util/knative/knative.go | 166 ---------
pkg/util/knative/uri.go | 104 ------
pkg/util/knative/uri_test.go | 98 -----
pkg/util/kubernetes/camel_labels.go | 74 ----
pkg/util/kubernetes/collection.go | 437 -----------------------
pkg/util/kubernetes/customclient/customclient.go | 85 -----
pkg/util/kubernetes/customclient/scheme.go | 66 ----
pkg/util/kubernetes/errors.go | 26 --
pkg/util/kubernetes/loader.go | 76 ----
pkg/util/kubernetes/log/annotation_scraper.go | 173 ---------
pkg/util/kubernetes/log/pod_scraper.go | 215 -----------
pkg/util/kubernetes/log/util.go | 41 ---
pkg/util/kubernetes/permission.go | 54 ---
pkg/util/kubernetes/replace.go | 150 --------
pkg/util/kubernetes/resolver.go | 132 -------
pkg/util/kubernetes/sanitize.go | 52 ---
pkg/util/kubernetes/sanitize_test.go | 46 ---
pkg/util/kubernetes/util.go | 245 -------------
pkg/util/kubernetes/wait.go | 72 ----
pkg/util/log/log.go | 196 ----------
pkg/util/maven/maven.go | 168 ---------
pkg/util/maven/maven_project.go | 199 -----------
pkg/util/maven/maven_project_test.go | 235 ------------
pkg/util/maven/maven_settings.go | 113 ------
pkg/util/maven/maven_settings_test.go | 239 -------------
pkg/util/maven/maven_types.go | 237 ------------
pkg/util/minikube/registry.go | 66 ----
pkg/util/monitoring/register.go | 47 ---
pkg/util/olm/available.go | 62 ----
pkg/util/olm/operator.go | 292 ---------------
pkg/util/openshift/openshift.go | 34 --
pkg/util/openshift/register.go | 66 ----
pkg/util/patch/patch.go | 91 -----
pkg/util/registry/registry.go | 97 -----
pkg/util/registry/registry_test.go | 68 ----
pkg/util/source/inspector.go | 320 -----------------
pkg/util/source/inspector_groovy.go | 62 ----
pkg/util/source/inspector_java_script.go | 62 ----
pkg/util/source/inspector_java_source.go | 58 ---
pkg/util/source/inspector_kotlin.go | 58 ---
pkg/util/source/inspector_xml.go | 86 -----
pkg/util/source/inspector_yaml.go | 137 -------
pkg/util/source/inspector_yaml_test.go | 106 ------
pkg/util/source/types.go | 50 ---
pkg/util/sync/file.go | 57 ---
pkg/util/sync/file_test.go | 69 ----
pkg/util/test/assertions.go | 52 ---
pkg/util/test/catalog_test.go | 43 ---
pkg/util/test/client.go | 67 ----
pkg/util/test/cmd.go | 46 ---
pkg/util/uri/uri.go | 58 ---
pkg/util/uri/uri_test.go | 91 -----
pkg/util/util.go | 223 ------------
pkg/util/watch/watch.go | 311 ----------------
pkg/util/zip/zip.go | 64 ----
78 files changed, 8309 deletions(-)
diff --git a/pkg/apis/addtoscheme_knative_eventing.go b/pkg/apis/addtoscheme_knative_eventing.go
deleted file mode 100644
index ef0486b..0000000
--- a/pkg/apis/addtoscheme_knative_eventing.go
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package apis
-
-import (
- eventingv1alpha1 "knative.dev/eventing/pkg/apis/eventing/v1alpha1"
- eventingv1beta1 "knative.dev/eventing/pkg/apis/eventing/v1beta1"
- messagingv1alpha1 "knative.dev/eventing/pkg/apis/messaging/v1alpha1"
- messagingv1beta1 "knative.dev/eventing/pkg/apis/messaging/v1beta1"
-)
-
-func init() {
- // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back
- AddToSchemes = append(AddToSchemes, eventingv1alpha1.AddToScheme)
- AddToSchemes = append(AddToSchemes, eventingv1beta1.AddToScheme)
- AddToSchemes = append(AddToSchemes, messagingv1alpha1.AddToScheme)
- AddToSchemes = append(AddToSchemes, messagingv1beta1.AddToScheme)
-}
diff --git a/pkg/apis/addtoscheme_knative_serving.go b/pkg/apis/addtoscheme_knative_serving.go
deleted file mode 100644
index f270608..0000000
--- a/pkg/apis/addtoscheme_knative_serving.go
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package apis
-
-import (
- serving "knative.dev/serving/pkg/apis/serving/v1"
-)
-
-func init() {
- // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back
- AddToSchemes = append(AddToSchemes, serving.AddToScheme)
-}
diff --git a/pkg/apis/addtoscheme_monitoring.go b/pkg/apis/addtoscheme_monitoring.go
deleted file mode 100644
index 248772d..0000000
--- a/pkg/apis/addtoscheme_monitoring.go
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package apis
-
-import "github.com/apache/camel-k/pkg/util/monitoring"
-
-func init() {
- // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back
- AddToSchemes = append(AddToSchemes, monitoring.AddToScheme)
-}
diff --git a/pkg/apis/addtoscheme_olm.go b/pkg/apis/addtoscheme_olm.go
deleted file mode 100644
index d891e98..0000000
--- a/pkg/apis/addtoscheme_olm.go
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package apis
-
-import (
- olmv1 "github.com/operator-framework/operator-lifecycle-manager/pkg/api/apis/operators/v1"
- olmv1alpha1 "github.com/operator-framework/operator-lifecycle-manager/pkg/api/apis/operators/v1alpha1"
-)
-
-func init() {
- // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back
- AddToSchemes = append(AddToSchemes, olmv1alpha1.AddToScheme)
- AddToSchemes = append(AddToSchemes, olmv1.AddToScheme)
-}
diff --git a/pkg/apis/addtoscheme_openshift.go b/pkg/apis/addtoscheme_openshift.go
deleted file mode 100644
index 13f6b53..0000000
--- a/pkg/apis/addtoscheme_openshift.go
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package apis
-
-import "github.com/apache/camel-k/pkg/util/openshift"
-
-func init() {
- // Register the types with the Scheme so the components can map objects to GroupVersionKinds and back
- AddToSchemes = append(AddToSchemes, openshift.AddToScheme)
-}
diff --git a/pkg/util/camel/camel_runtime.go b/pkg/util/camel/camel_runtime.go
deleted file mode 100644
index 2d6a345..0000000
--- a/pkg/util/camel/camel_runtime.go
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package camel
-
-import (
- "context"
-
- k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/client"
-)
-
-// LoadCatalog --
-func LoadCatalog(ctx context.Context, client client.Client, namespace string, runtime v1.RuntimeSpec) (*RuntimeCatalog, error) {
- options := []k8sclient.ListOption{
- k8sclient.InNamespace(namespace),
- k8sclient.MatchingLabels{
- "camel.apache.org/runtime.provider": string(runtime.Provider),
- },
- }
-
- list := v1.NewCamelCatalogList()
- err := client.List(ctx, &list, options...)
- if err != nil {
- return nil, err
- }
-
- catalog, err := findBestMatch(list.Items, runtime)
- if err != nil {
- return nil, err
- }
-
- return catalog, nil
-}
diff --git a/pkg/util/camel/camel_runtime_catalog.go b/pkg/util/camel/camel_runtime_catalog.go
deleted file mode 100644
index 8153299..0000000
--- a/pkg/util/camel/camel_runtime_catalog.go
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package camel
-
-import (
- "strings"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
-)
-
-// NewRuntimeCatalog --
-func NewRuntimeCatalog(spec v1.CamelCatalogSpec) *RuntimeCatalog {
- catalog := RuntimeCatalog{}
- catalog.CamelCatalogSpec = spec
- catalog.artifactByScheme = make(map[string]string)
- catalog.schemesByID = make(map[string]v1.CamelScheme)
- catalog.languageDependencies = make(map[string]string)
- catalog.javaTypeDependencies = make(map[string]string)
-
- for id, artifact := range catalog.Artifacts {
- for _, scheme := range artifact.Schemes {
- scheme := scheme
- catalog.artifactByScheme[scheme.ID] = id
- catalog.schemesByID[scheme.ID] = scheme
- }
- for _, language := range artifact.Languages {
- // Skip languages in common dependencies since they are always available to integrations
- if artifact.ArtifactID != "camel-base" {
- catalog.languageDependencies[language] = getDependency(artifact, catalog.Runtime.Provider)
- }
- }
- for _, javaType := range artifact.JavaTypes {
- // Skip types in common dependencies since they are always available to integrations
- if artifact.ArtifactID != "camel-base" {
- catalog.javaTypeDependencies[javaType] = getDependency(artifact, catalog.Runtime.Provider)
- }
- }
- }
-
- return &catalog
-}
-
-// RuntimeCatalog --
-type RuntimeCatalog struct {
- v1.CamelCatalogSpec
-
- artifactByScheme map[string]string
- schemesByID map[string]v1.CamelScheme
- languageDependencies map[string]string
- javaTypeDependencies map[string]string
-}
-
-// HasArtifact --
-func (c *RuntimeCatalog) HasArtifact(artifact string) bool {
- if !strings.HasPrefix(artifact, "camel-") {
- artifact = "camel-" + artifact
- }
-
- _, ok := c.Artifacts[artifact]
-
- return ok
-}
-
-// GetArtifactByScheme returns the artifact corresponding to the given component scheme
-func (c *RuntimeCatalog) GetArtifactByScheme(scheme string) *v1.CamelArtifact {
- if id, ok := c.artifactByScheme[scheme]; ok {
- if artifact, present := c.Artifacts[id]; present {
- return &artifact
- }
- }
- return nil
-}
-
-// GetScheme returns the scheme definition for the given scheme id
-func (c *RuntimeCatalog) GetScheme(id string) (v1.CamelScheme, bool) {
- scheme, ok := c.schemesByID[id]
- return scheme, ok
-}
-
-// GetLanguageDependency returns the maven dependency for the given language name
-func (c *RuntimeCatalog) GetLanguageDependency(language string) (string, bool) {
- language, ok := c.languageDependencies[language]
- return language, ok
-}
-
-// GetJavaTypeDependency returns the maven dependency for the given type name
-func (c *RuntimeCatalog) GetJavaTypeDependency(camelType string) (string, bool) {
- javaType, ok := c.javaTypeDependencies[camelType]
- return javaType, ok
-}
-
-// VisitArtifacts --
-func (c *RuntimeCatalog) VisitArtifacts(visitor func(string, v1.CamelArtifact) bool) {
- for id, artifact := range c.Artifacts {
- if !visitor(id, artifact) {
- break
- }
- }
-}
-
-// VisitSchemes --
-func (c *RuntimeCatalog) VisitSchemes(visitor func(string, v1.CamelScheme) bool) {
- for id, scheme := range c.schemesByID {
- if !visitor(id, scheme) {
- break
- }
- }
-}
diff --git a/pkg/util/camel/camel_types.go b/pkg/util/camel/camel_types.go
deleted file mode 100644
index 7dd776a..0000000
--- a/pkg/util/camel/camel_types.go
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package camel
-
-import (
- "github.com/Masterminds/semver"
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
-)
-
-// CatalogVersion --
-type CatalogVersion struct {
- RuntimeVersion *semver.Version
- Catalog *v1.CamelCatalog
-}
-
-// CatalogVersionCollection --
-type CatalogVersionCollection []CatalogVersion
-
-// Len returns the length of a collection. The number of CatalogVersion instances
-// on the slice.
-func (c CatalogVersionCollection) Len() int {
- return len(c)
-}
-
-// Less is needed for the sort interface to compare two CatalogVersion objects on the
-// slice. If checks if one is less than the other.
-func (c CatalogVersionCollection) Less(i, j int) bool {
- return c[i].RuntimeVersion.LessThan(c[j].RuntimeVersion)
-}
-
-// Swap is needed for the sort interface to replace the CatalogVersion objects
-// at two different positions in the slice.
-func (c CatalogVersionCollection) Swap(i, j int) {
- c[i], c[j] = c[j], c[i]
-}
diff --git a/pkg/util/camel/camel_util.go b/pkg/util/camel/camel_util.go
deleted file mode 100644
index 055eefe..0000000
--- a/pkg/util/camel/camel_util.go
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package camel
-
-import (
- "sort"
- "strings"
-
- "github.com/Masterminds/semver"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/util/log"
-)
-
-func findBestMatch(catalogs []v1.CamelCatalog, runtime v1.RuntimeSpec) (*RuntimeCatalog, error) {
- for _, catalog := range catalogs {
- if catalog.Spec.Runtime.Version == runtime.Version && catalog.Spec.Runtime.Provider == runtime.Provider {
- return NewRuntimeCatalog(catalog.Spec), nil
- }
- }
-
- rc := newSemVerConstraint(runtime.Version)
- if rc == nil {
- return nil, nil
- }
-
- cc := newCatalogVersionCollection(catalogs)
- for _, c := range cc {
- if rc.Check(c.RuntimeVersion) {
- return NewRuntimeCatalog(c.Catalog.Spec), nil
- }
- }
-
- return nil, nil
-}
-
-func newSemVerConstraint(versionConstraint string) *semver.Constraints {
- constraint, err := semver.NewConstraint(versionConstraint)
- if err != nil || constraint == nil {
- if err != nil {
- log.Debug("Unable to parse version constraint: %s, error:\n", versionConstraint, err.Error())
- }
- if constraint == nil {
- log.Debug("Unable to parse version constraint: %s\n", versionConstraint)
- }
- }
-
- return constraint
-}
-
-func newCatalogVersionCollection(catalogs []v1.CamelCatalog) CatalogVersionCollection {
- versions := make([]CatalogVersion, 0, len(catalogs))
-
- for i := range catalogs {
- rv, err := semver.NewVersion(catalogs[i].Spec.Runtime.Version)
- if err != nil {
- log.Debugf("Invalid semver version (runtime) %s", rv)
- continue
- }
-
- versions = append(versions, CatalogVersion{
- RuntimeVersion: rv,
- Catalog: &catalogs[i],
- })
- }
-
- answer := CatalogVersionCollection(versions)
-
- sort.Sort(
- sort.Reverse(answer),
- )
-
- return answer
-}
-
-func getDependency(artifact v1.CamelArtifact, runtimeProvider v1.RuntimeProvider) string {
- if runtimeProvider == v1.RuntimeProviderQuarkus {
- return strings.Replace(artifact.ArtifactID, "camel-quarkus-", "camel-quarkus:", 1)
- }
- return strings.Replace(artifact.ArtifactID, "camel-", "camel:", 1)
-}
diff --git a/pkg/util/camel/camel_util_test.go b/pkg/util/camel/camel_util_test.go
deleted file mode 100644
index 2caec80..0000000
--- a/pkg/util/camel/camel_util_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package camel
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
-)
-
-func TestFindBestMatch(t *testing.T) {
- catalogs := []v1.CamelCatalog{
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.0", Provider: v1.RuntimeProviderMain}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.1", Provider: v1.RuntimeProviderMain}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.0", Provider: v1.RuntimeProviderQuarkus}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.1", Provider: v1.RuntimeProviderQuarkus}}},
- }
-
- c, err := findBestMatch(catalogs, v1.RuntimeSpec{Version: "~1.0.x", Provider: v1.RuntimeProviderMain})
- assert.Nil(t, err)
- assert.NotNil(t, c)
- assert.Equal(t, "1.0.1", c.Runtime.Version)
- assert.Equal(t, v1.RuntimeProviderMain, c.Runtime.Provider)
-}
-
-func TestFindExactSemVerMatch(t *testing.T) {
- catalogs := []v1.CamelCatalog{
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.0", Provider: v1.RuntimeProviderMain}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.1", Provider: v1.RuntimeProviderMain}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.0", Provider: v1.RuntimeProviderQuarkus}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.1", Provider: v1.RuntimeProviderQuarkus}}},
- }
-
- c, err := findBestMatch(catalogs, v1.RuntimeSpec{Version: "1.0.0", Provider: v1.RuntimeProviderMain})
- assert.Nil(t, err)
- assert.NotNil(t, c)
- assert.Equal(t, "1.0.0", c.Runtime.Version)
- assert.Equal(t, v1.RuntimeProviderMain, c.Runtime.Provider)
-}
-
-func TestFindRangeMatch(t *testing.T) {
- catalogs := []v1.CamelCatalog{
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.0", Provider: v1.RuntimeProviderMain}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.1", Provider: v1.RuntimeProviderMain}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.2", Provider: v1.RuntimeProviderMain}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.0", Provider: v1.RuntimeProviderQuarkus}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.1", Provider: v1.RuntimeProviderQuarkus}}},
- {Spec: v1.CamelCatalogSpec{Runtime: v1.RuntimeSpec{Version: "1.0.2", Provider: v1.RuntimeProviderQuarkus}}},
- }
-
- c, err := findBestMatch(catalogs, v1.RuntimeSpec{Version: "> 1.0.1, < 1.0.3", Provider: v1.RuntimeProviderMain})
- assert.Nil(t, err)
- assert.NotNil(t, c)
- assert.Equal(t, "1.0.2", c.Runtime.Version)
- assert.Equal(t, v1.RuntimeProviderMain, c.Runtime.Provider)
-}
diff --git a/pkg/util/cancellable/cancellable.go b/pkg/util/cancellable/cancellable.go
deleted file mode 100644
index 3e90d31..0000000
--- a/pkg/util/cancellable/cancellable.go
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package cancellable
-
-import "context"
-
-// Context --
-type Context interface {
- context.Context
-
- Cancel()
-}
-
-// NewContext --
-func NewContext() Context {
- return NewContextWithParent(context.TODO())
-}
-
-// NewContextWithParent --
-func NewContextWithParent(parent context.Context) Context {
- c, cc := context.WithCancel(parent)
-
- return &cancellableContext{
- Context: c,
- cancel: cc,
- }
-}
-
-type cancellableContext struct {
- context.Context
- cancel func()
-}
-
-func (c *cancellableContext) Cancel() {
- c.cancel()
-}
diff --git a/pkg/util/config/config.go b/pkg/util/config/config.go
deleted file mode 100644
index 8ab6ad0..0000000
--- a/pkg/util/config/config.go
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package config
diff --git a/pkg/util/controller/util.go b/pkg/util/controller/util.go
deleted file mode 100644
index b80c94e..0000000
--- a/pkg/util/controller/util.go
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package controller
-
-import (
- "k8s.io/apimachinery/pkg/labels"
- "k8s.io/apimachinery/pkg/selection"
- "sigs.k8s.io/controller-runtime/pkg/client"
-)
-
-type MatchingSelector struct {
- Selector labels.Selector
-}
-
-func (s MatchingSelector) ApplyToList(opts *client.ListOptions) {
- opts.LabelSelector = s.Selector
-}
-
-func (s MatchingSelector) ApplyToDeleteAllOf(opts *client.DeleteAllOfOptions) {
- opts.LabelSelector = s.Selector
-}
-
-func NewLabelSelector(key string, op selection.Operator, values []string) MatchingSelector {
- provider, _ := labels.NewRequirement(key, op, values)
- selector := labels.NewSelector().Add(*provider)
-
- return MatchingSelector{
- Selector: selector,
- }
-}
diff --git a/pkg/util/defaults/defaults.go b/pkg/util/defaults/defaults.go
deleted file mode 100644
index 91febcb..0000000
--- a/pkg/util/defaults/defaults.go
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package defaults
-
-// ***********************
-// DO NOT EDIT THIS FILE
-// ***********************
-
-const (
- // Version --
- Version = "1.0.0-SNAPSHOT"
-
- // DefaultRuntimeVersion --
- DefaultRuntimeVersion = "1.3.0-SNAPSHOT"
-
- // BuildahVersion --
- BuildahVersion = "1.14.0"
-
- // KanikoVersion --
- KanikoVersion = "0.17.1"
-
- // BaseImage --
- BaseImage = "adoptopenjdk/openjdk11:slim"
-
- // LocalRepository --
- LocalRepository = "/tmp/artifacts/m2"
-
- // ImageName --
- ImageName = "docker.io/apache/camel-k"
-)
diff --git a/pkg/util/digest/digest.go b/pkg/util/digest/digest.go
deleted file mode 100644
index c79f045..0000000
--- a/pkg/util/digest/digest.go
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package digest
-
-import (
- // nolint: gosec
- "crypto/sha1"
- "crypto/sha256"
- "encoding/base64"
- "io"
- "os"
- "path"
- "sort"
- "strconv"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/util"
- "github.com/apache/camel-k/pkg/util/defaults"
-)
-
-// ComputeForIntegration a digest of the fields that are relevant for the deployment
-// Produces a digest that can be used as docker image tag
-func ComputeForIntegration(integration *v1.Integration) (string, error) {
- hash := sha256.New()
- // Operator version is relevant
- if _, err := hash.Write([]byte(defaults.Version)); err != nil {
- return "", err
- }
- // Integration Kit is relevant
- if _, err := hash.Write([]byte(integration.Spec.Kit)); err != nil {
- return "", err
- }
- // Profile is relevant
- if _, err := hash.Write([]byte(integration.Spec.Profile)); err != nil {
- return "", err
- }
-
- // Integration code
- for _, s := range integration.Spec.Sources {
- if s.Content != "" {
- if _, err := hash.Write([]byte(s.Content)); err != nil {
- return "", err
- }
- }
- }
-
- // Integration resources
- for _, item := range integration.Spec.Resources {
- if _, err := hash.Write([]byte(item.Content)); err != nil {
- return "", err
- }
- }
-
- // Integration dependencies
- for _, item := range integration.Spec.Dependencies {
- if _, err := hash.Write([]byte(item)); err != nil {
- return "", err
- }
- }
-
- // Integration configuration
- for _, item := range integration.Spec.Configuration {
- if _, err := hash.Write([]byte(item.String())); err != nil {
- return "", err
- }
- }
-
- // Integration traits
- for _, name := range sortedTraitSpecMapKeys(integration.Spec.Traits) {
- if _, err := hash.Write([]byte(name + "[")); err != nil {
- return "", err
- }
- spec := integration.Spec.Traits[name]
- for _, prop := range util.SortedStringMapKeys(spec.Configuration) {
- val := spec.Configuration[prop]
- if _, err := hash.Write([]byte(prop + "=" + val + ",")); err != nil {
- return "", err
- }
- }
- if _, err := hash.Write([]byte("]")); err != nil {
- return "", err
- }
- }
-
- // Add a letter at the beginning and use URL safe encoding
- digest := "v" + base64.RawURLEncoding.EncodeToString(hash.Sum(nil))
- return digest, nil
-}
-
-// ComputeForIntegrationKit a digest of the fields that are relevant for the deployment
-// Produces a digest that can be used as docker image tag
-func ComputeForIntegrationKit(kit *v1.IntegrationKit) (string, error) {
- hash := sha256.New()
- // Operator version is relevant
- if _, err := hash.Write([]byte(defaults.Version)); err != nil {
- return "", err
- }
-
- for _, item := range kit.Spec.Dependencies {
- if _, err := hash.Write([]byte(item)); err != nil {
- return "", err
- }
- }
- for _, item := range kit.Spec.Configuration {
- if _, err := hash.Write([]byte(item.String())); err != nil {
- return "", err
- }
- }
-
- // Add a letter at the beginning and use URL safe encoding
- digest := "v" + base64.RawURLEncoding.EncodeToString(hash.Sum(nil))
- return digest, nil
-}
-
-// ComputeForResource returns a digest for the specific resource
-func ComputeForResource(res v1.ResourceSpec) (string, error) {
- hash := sha256.New()
- // Operator version is relevant
- if _, err := hash.Write([]byte(defaults.Version)); err != nil {
- return "", err
- }
-
- if _, err := hash.Write([]byte(res.Content)); err != nil {
- return "", err
- }
- if _, err := hash.Write([]byte(res.Name)); err != nil {
- return "", err
- }
- if _, err := hash.Write([]byte(res.Type)); err != nil {
- return "", err
- }
- if _, err := hash.Write([]byte(res.ContentKey)); err != nil {
- return "", err
- }
- if _, err := hash.Write([]byte(res.ContentRef)); err != nil {
- return "", err
- }
- if _, err := hash.Write([]byte(res.MountPath)); err != nil {
- return "", err
- }
- if _, err := hash.Write([]byte(strconv.FormatBool(res.Compression))); err != nil {
- return "", err
- }
-
- // Add a letter at the beginning and use URL safe encoding
- digest := "v" + base64.RawURLEncoding.EncodeToString(hash.Sum(nil))
- return digest, nil
-}
-
-func sortedTraitSpecMapKeys(m map[string]v1.TraitSpec) []string {
- res := make([]string, len(m))
- i := 0
- for k := range m {
- res[i] = k
- i++
- }
- sort.Strings(res)
- return res
-}
-
-// ComputeSHA1 ---
-func ComputeSHA1(elem ...string) (string, error) {
- file := path.Join(elem...)
-
- f, err := os.Open(file)
- if err != nil {
- return "", err
- }
- defer f.Close()
-
- // nolint: gosec
- h := sha1.New()
- if _, err := io.Copy(h, f); err != nil {
- return "", err
- }
-
- return base64.StdEncoding.EncodeToString(h.Sum(nil)), nil
-}
diff --git a/pkg/util/envvar/envvar.go b/pkg/util/envvar/envvar.go
deleted file mode 100644
index 806c818..0000000
--- a/pkg/util/envvar/envvar.go
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package envvar
-
-import corev1 "k8s.io/api/core/v1"
-
-// Get --
-func Get(vars []corev1.EnvVar, name string) *corev1.EnvVar {
- for i := 0; i < len(vars); i++ {
- if vars[i].Name == name {
- return &vars[i]
- }
- }
-
- return nil
-}
-
-// Remove --
-func Remove(vars *[]corev1.EnvVar, name string) {
- v := *vars
- for i := 0; i < len(v); i++ {
- if v[i].Name == name {
- v = append(v[:i], v[i+1:]...)
- *vars = v
- return
- }
- }
-}
-
-// SetVal --
-func SetVal(vars *[]corev1.EnvVar, name string, value string) {
- envVar := Get(*vars, name)
-
- if envVar != nil {
- envVar.Value = value
- envVar.ValueFrom = nil
- } else {
- *vars = append(*vars, corev1.EnvVar{
- Name: name,
- Value: value,
- })
- }
-}
-
-// SetVar --
-func SetVar(vars *[]corev1.EnvVar, newEnvVar corev1.EnvVar) {
- envVar := Get(*vars, newEnvVar.Name)
-
- if envVar != nil {
- envVar.Value = newEnvVar.Value
- envVar.ValueFrom = nil
-
- if newEnvVar.ValueFrom != nil {
- from := *newEnvVar.ValueFrom
- envVar.ValueFrom = &from
- }
- } else {
- *vars = append(*vars, newEnvVar)
- }
-}
-
-// SetValFrom --
-func SetValFrom(vars *[]corev1.EnvVar, name string, path string) {
- envVar := Get(*vars, name)
-
- if envVar != nil {
- envVar.Value = ""
- envVar.ValueFrom = &corev1.EnvVarSource{
- FieldRef: &corev1.ObjectFieldSelector{
- FieldPath: path,
- },
- }
- } else {
- *vars = append(*vars, corev1.EnvVar{
- Name: name,
- ValueFrom: &corev1.EnvVarSource{
- FieldRef: &corev1.ObjectFieldSelector{
- FieldPath: path,
- },
- },
- })
- }
-}
diff --git a/pkg/util/envvar/envvar_test.go b/pkg/util/envvar/envvar_test.go
deleted file mode 100644
index 041341d..0000000
--- a/pkg/util/envvar/envvar_test.go
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package envvar
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-
- corev1 "k8s.io/api/core/v1"
-)
-
-func TestGetEnvVar(t *testing.T) {
- vars := []corev1.EnvVar{
- {
- Name: "MyEnv",
- Value: "MyValue",
- },
- }
-
- ev := Get(vars, "MyEnv")
-
- assert.NotNil(t, ev)
- assert.Equal(t, "MyValue", ev.Value)
- assert.Nil(t, ev.ValueFrom)
-
- assert.Nil(t, Get(vars, "NotMyEnv"))
-}
-
-func TestModifyEnvVar(t *testing.T) {
- vars := []corev1.EnvVar{
- {
- Name: "MyEnv",
- Value: "MyValue",
- },
- }
-
- ev := Get(vars, "MyEnv")
- assert.NotNil(t, ev)
- assert.Equal(t, "MyValue", ev.Value)
-
- ev.Value = "MyNewValue"
-
- ev = Get(vars, "MyEnv")
- assert.NotNil(t, ev)
- assert.Equal(t, "MyNewValue", ev.Value)
-}
-
-func TestSetEnvVar(t *testing.T) {
- vars := []corev1.EnvVar{
- {
- Name: "MyEnv",
- Value: "MyValue",
- },
- }
-
- ev := Get(vars, "MyEnv")
- assert.NotNil(t, ev)
- assert.Equal(t, "MyValue", ev.Value)
- assert.Nil(t, ev.ValueFrom)
-
- SetVal(&vars, "MyEnv", "MyNewValue")
-
- ev = Get(vars, "MyEnv")
- assert.NotNil(t, ev)
- assert.Equal(t, "MyNewValue", ev.Value)
- assert.Nil(t, ev.ValueFrom)
-
- SetVal(&vars, "MyNewEnv", "MyNewNewValue")
-
- ev = Get(vars, "MyEnv")
- assert.NotNil(t, ev)
- assert.Equal(t, "MyNewValue", ev.Value)
- assert.Nil(t, ev.ValueFrom)
-
- ev = Get(vars, "MyNewEnv")
- assert.NotNil(t, ev)
- assert.Equal(t, "MyNewNewValue", ev.Value)
- assert.Nil(t, ev.ValueFrom)
-
- SetValFrom(&vars, "MyNewEnv", "metadata.namespace")
-
- ev = Get(vars, "MyNewEnv")
- assert.NotNil(t, ev)
- assert.Equal(t, "", ev.Value)
- assert.NotNil(t, ev.ValueFrom)
- assert.Equal(t, "metadata.namespace", ev.ValueFrom.FieldRef.FieldPath)
-}
diff --git a/pkg/util/gzip/compress.go b/pkg/util/gzip/compress.go
deleted file mode 100644
index ede1ff2..0000000
--- a/pkg/util/gzip/compress.go
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package gzip
-
-import (
- "bytes"
- g "compress/gzip"
- "encoding/base64"
- "io"
- "io/ioutil"
-)
-
-// Compress --
-func Compress(buffer io.Writer, data []byte) error {
- gz := g.NewWriter(buffer)
-
- if _, err := gz.Write(data); err != nil {
- return err
- }
- if err := gz.Flush(); err != nil {
- return err
- }
- if err := gz.Close(); err != nil {
- return err
- }
-
- return nil
-}
-
-// CompressBase64 --
-func CompressBase64(data []byte) ([]byte, error) {
- var b bytes.Buffer
-
- if err := Compress(&b, data); err != nil {
- return []byte{}, err
- }
-
- return []byte(base64.StdEncoding.EncodeToString(b.Bytes())), nil
-}
-
-// Uncompress --
-func Uncompress(buffer io.Writer, data []byte) error {
- b := bytes.NewBuffer(data)
- gz, err := g.NewReader(b)
- if err != nil {
- return err
- }
-
- defer gz.Close()
-
- data, err = ioutil.ReadAll(gz)
- if err != nil {
- return err
- }
-
- _, err = buffer.Write(data)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// UncompressBase64 --
-func UncompressBase64(data []byte) ([]byte, error) {
- d, err := base64.StdEncoding.DecodeString(string(data))
- if err != nil {
- return []byte{}, err
- }
-
- var b bytes.Buffer
- err = Uncompress(&b, d)
- if err != nil {
- return []byte{}, err
- }
-
- return b.Bytes(), nil
-}
diff --git a/pkg/util/gzip/compress_test.go b/pkg/util/gzip/compress_test.go
deleted file mode 100644
index 97cc195..0000000
--- a/pkg/util/gzip/compress_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package gzip
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestCompression(t *testing.T) {
- source := "this is a script"
- compressed, err := CompressBase64([]byte(source))
- assert.Nil(t, err)
- uncompressed, err := UncompressBase64(compressed)
- assert.Nil(t, err)
- assert.Equal(t, source, string(uncompressed))
-}
diff --git a/pkg/util/indentedwriter/writer.go b/pkg/util/indentedwriter/writer.go
deleted file mode 100644
index cab0e8c..0000000
--- a/pkg/util/indentedwriter/writer.go
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package indentedwriter
-
-import (
- "bytes"
- "fmt"
- "io"
- "strings"
- "text/tabwriter"
-)
-
-// Flusher --
-type Flusher interface {
- Flush()
-}
-
-// Writer --.
-type Writer struct {
- out io.Writer
-}
-
-// NewWriter --
-func NewWriter(out io.Writer) *Writer {
- return &Writer{out: out}
-}
-
-// Write --
-func (iw *Writer) Write(indentLevel int, format string, i ...interface{}) {
- fmt.Fprint(iw.out, strings.Repeat(" ", indentLevel))
- fmt.Fprintf(iw.out, format, i...)
-}
-
-// Writeln --
-func (iw *Writer) Writeln(indentLevel int, format string, i ...interface{}) {
- fmt.Fprint(iw.out, strings.Repeat(" ", indentLevel))
- fmt.Fprintf(iw.out, format, i...)
- fmt.Fprint(iw.out, "\n")
-}
-
-// Flush --
-func (iw *Writer) Flush() {
- if f, ok := iw.out.(Flusher); ok {
- f.Flush()
- }
-}
-
-// IndentedString --
-func IndentedString(f func(io.Writer)) string {
- var out tabwriter.Writer
- buf := &bytes.Buffer{}
- out.Init(buf, 0, 8, 2, ' ', 0)
-
- f(&out)
-
- out.Flush()
-
- return buf.String()
-}
diff --git a/pkg/util/knative/apis.go b/pkg/util/knative/apis.go
deleted file mode 100644
index fbe26ce..0000000
--- a/pkg/util/knative/apis.go
+++ /dev/null
@@ -1,225 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package knative
-
-import (
- knativev1 "github.com/apache/camel-k/pkg/apis/camel/v1/knative"
- "github.com/apache/camel-k/pkg/util"
- v1 "k8s.io/api/core/v1"
- "k8s.io/apimachinery/pkg/runtime/schema"
-)
-
-var (
- // KnownChannelKinds are known channel kinds belonging to Knative
- KnownChannelKinds = []GroupVersionKindResource{
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "Channel",
- Group: "messaging.knative.dev",
- Version: "v1beta1",
- },
- Resource: "channels",
- },
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "Channel",
- Group: "messaging.knative.dev",
- Version: "v1alpha1",
- },
- Resource: "channels",
- },
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "Channel",
- Group: "eventing.knative.dev",
- Version: "v1alpha1",
- },
- Resource: "channels",
- },
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "InMemoryChannel",
- Group: "messaging.knative.dev",
- Version: "v1beta1",
- },
- Resource: "inmemorychannels",
- },
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "InMemoryChannel",
- Group: "messaging.knative.dev",
- Version: "v1alpha1",
- },
- Resource: "inmemorychannels",
- },
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "KafkaChannel",
- Group: "messaging.knative.dev",
- Version: "v1alpha1",
- },
- Resource: "kafkachannels",
- },
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "NatssChannel",
- Group: "messaging.knative.dev",
- Version: "v1alpha1",
- },
- Resource: "natsschannels",
- },
- }
-
- // KnownEndpointKinds are known endpoint kinds belonging to Knative
- KnownEndpointKinds = []GroupVersionKindResource{
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "Service",
- Group: "serving.knative.dev",
- Version: "v1",
- },
- Resource: "services",
- },
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "Service",
- Group: "serving.knative.dev",
- Version: "v1beta1",
- },
- Resource: "services",
- },
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "Service",
- Group: "serving.knative.dev",
- Version: "v1alpha1",
- },
- Resource: "services",
- },
- }
-
- // KnownBrokerKinds are known broker kinds belonging to Knative
- KnownBrokerKinds = []GroupVersionKindResource{
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "Broker",
- Group: "eventing.knative.dev",
- Version: "v1beta1",
- },
- Resource: "brokers",
- },
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "Broker",
- Group: "eventing.knative.dev",
- Version: "v1alpha1",
- },
- Resource: "brokers",
- },
- }
-
- // RequiredKinds are Knative kinds used by Camel K for materializing integrations.
- // They must be present on the cluster
- RequiredKinds = []GroupVersionKindResource{
- {
- GroupVersionKind: schema.GroupVersionKind{
- Kind: "Service",
- Group: "serving.knative.dev",
- Version: "v1",
- },
- Resource: "services",
- },
- }
-)
-
-// GroupVersionKindResource --
-type GroupVersionKindResource struct {
- schema.GroupVersionKind
- Resource string
-}
-
-func init() {
- // Channels are also endpoints
- KnownEndpointKinds = append(KnownEndpointKinds, KnownChannelKinds...)
- // Let's add the brokers as last
- KnownEndpointKinds = append(KnownEndpointKinds, KnownBrokerKinds...)
-}
-
-// FillMissingReferenceData returns all possible combinations of ObjectReference that can be obtained by filling the missing fields
-// with known data.
-func FillMissingReferenceData(serviceType knativev1.CamelServiceType, ref v1.ObjectReference) []v1.ObjectReference {
- var refs []v1.ObjectReference
- switch serviceType {
- case knativev1.CamelServiceTypeChannel:
- refs = fillMissingReferenceDataWith(KnownChannelKinds, ref)
- case knativev1.CamelServiceTypeEndpoint:
- refs = fillMissingReferenceDataWith(KnownEndpointKinds, ref)
- case knativev1.CamelServiceTypeEvent:
- refs = fillMissingReferenceDataWith(KnownBrokerKinds, ref)
- }
-
- return refs
-}
-
-// nolint: gocritic
-func fillMissingReferenceDataWith(serviceTypes []GroupVersionKindResource, ref v1.ObjectReference) []v1.ObjectReference {
- list := make([]v1.ObjectReference, 0)
- if ref.APIVersion == "" && ref.Kind == "" {
- for _, st := range serviceTypes {
- refCopy := ref.DeepCopy()
- refCopy.APIVersion = st.GroupVersion().String()
- refCopy.Kind = st.Kind
- list = append(list, *refCopy)
- }
- } else if ref.APIVersion == "" {
- for _, gv := range getGroupVersions(serviceTypes, ref.Kind) {
- refCopy := ref.DeepCopy()
- refCopy.APIVersion = gv
- list = append(list, *refCopy)
- }
- } else if ref.Kind == "" {
- for _, k := range getKinds(serviceTypes, ref.APIVersion) {
- refCopy := ref.DeepCopy()
- refCopy.Kind = k
- list = append(list, *refCopy)
- }
- } else {
- list = append(list, ref)
- }
- return list
-}
-
-func getGroupVersions(serviceTypes []GroupVersionKindResource, kind string) []string {
- res := make([]string, 0)
- for _, st := range serviceTypes {
- if st.Kind == kind {
- util.StringSliceUniqueAdd(&res, st.GroupVersion().String())
- }
- }
- return res
-}
-
-func getKinds(serviceTypes []GroupVersionKindResource, apiVersion string) []string {
- res := make([]string, 0)
- for _, st := range serviceTypes {
- if st.GroupVersion().String() == apiVersion {
- util.StringSliceUniqueAdd(&res, st.Kind)
- }
- }
- return res
-}
diff --git a/pkg/util/knative/apis_test.go b/pkg/util/knative/apis_test.go
deleted file mode 100644
index b1014b6..0000000
--- a/pkg/util/knative/apis_test.go
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package knative
-
-import (
- "testing"
-
- "github.com/apache/camel-k/pkg/apis/camel/v1/knative"
- "github.com/stretchr/testify/assert"
- v1 "k8s.io/api/core/v1"
-)
-
-func TestAPIs(t *testing.T) {
- ref, err := ExtractObjectReference("knative:endpoint/ciao")
- assert.Nil(t, err)
- refs := FillMissingReferenceData(knative.CamelServiceTypeEndpoint, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, v1.ObjectReference{
- Kind: "Service",
- APIVersion: "serving.knative.dev/v1",
- Name: "ciao",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:endpoint/ciao?apiVersion=serving.knative.dev/v1")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeEndpoint, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, 1, len(refs))
- assert.Equal(t, v1.ObjectReference{
- Kind: "Service",
- APIVersion: "serving.knative.dev/v1",
- Name: "ciao",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:endpoint/ciao?apiVersion=serving.knative.dev/v1&kind=Xxx")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeEndpoint, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, 1, len(refs))
- assert.Equal(t, v1.ObjectReference{
- Kind: "Xxx",
- APIVersion: "serving.knative.dev/v1",
- Name: "ciao",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:endpoint/ciao?apiVersion=yyy&kind=Xxx")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeEndpoint, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, 1, len(refs))
- assert.Equal(t, v1.ObjectReference{
- Kind: "Xxx",
- APIVersion: "yyy",
- Name: "ciao",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:endpoint/ciao?kind=Service")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeEndpoint, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, v1.ObjectReference{
- Kind: "Service",
- APIVersion: "serving.knative.dev/v1",
- Name: "ciao",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:endpoint/ciao?kind=Channel")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeEndpoint, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, v1.ObjectReference{
- Kind: "Channel",
- APIVersion: "messaging.knative.dev/v1beta1",
- Name: "ciao",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:endpoint/ciao?kind=KafkaChannel")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeEndpoint, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, v1.ObjectReference{
- Kind: "KafkaChannel",
- APIVersion: "messaging.knative.dev/v1alpha1",
- Name: "ciao",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:channel/ciao")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeChannel, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, v1.ObjectReference{
- Kind: "Channel",
- APIVersion: "messaging.knative.dev/v1beta1",
- Name: "ciao",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:channel/ciao?apiVersion=eventing.knative.dev/v1alpha1")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeChannel, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, v1.ObjectReference{
- Kind: "Channel",
- APIVersion: "eventing.knative.dev/v1alpha1",
- Name: "ciao",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:channel/ciao?apiVersion=xxx.knative.dev/v1alpha1")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeChannel, ref)
- assert.Equal(t, 0, len(refs))
-
- ref, err = ExtractObjectReference("knative:event/ciao")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeEvent, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, v1.ObjectReference{
- Kind: "Broker",
- APIVersion: "eventing.knative.dev/v1beta1",
- Name: "default",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:event/ciao?brokerApiVersion=xxx")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeEvent, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, v1.ObjectReference{
- Kind: "Broker",
- APIVersion: "xxx",
- Name: "default",
- }, refs[0])
-
- ref, err = ExtractObjectReference("knative:event/ciao?brokerName=aaa")
- assert.Nil(t, err)
- refs = FillMissingReferenceData(knative.CamelServiceTypeEvent, ref)
- checkValidRefs(t, refs)
- assert.Equal(t, v1.ObjectReference{
- Kind: "Broker",
- APIVersion: "eventing.knative.dev/v1beta1",
- Name: "aaa",
- }, refs[0])
-}
-
-func checkValidRefs(t *testing.T, refs []v1.ObjectReference) {
- assert.True(t, len(refs) > 0)
- for _, ref := range refs {
- assert.NotNil(t, ref.Name)
- assert.NotNil(t, ref.Kind)
- assert.NotNil(t, ref.APIVersion)
- }
-}
diff --git a/pkg/util/knative/enabled.go b/pkg/util/knative/enabled.go
deleted file mode 100644
index 8853e2d..0000000
--- a/pkg/util/knative/enabled.go
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package knative
-
-import (
- "context"
-
- "github.com/apache/camel-k/pkg/client"
- kubernetesutils "github.com/apache/camel-k/pkg/util/kubernetes"
- "github.com/apache/camel-k/pkg/util/log"
- k8serrors "k8s.io/apimachinery/pkg/api/errors"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/client-go/dynamic"
- "k8s.io/client-go/kubernetes"
-)
-
-// IsEnabledInNamespace returns true if we can list some basic knative objects in the given namespace.
-//
-// This method can be used at operator level to check if knative resources can be accessed.
-func IsEnabledInNamespace(ctx context.Context, c client.Client, namespace string) bool {
- dyn, err := dynamic.NewForConfig(c.GetConfig())
- if err != nil {
- log.Infof("could not create dynamic client to check knative installation in namespace %s, got error: %v", namespace, err)
- return false
- }
- for _, kgv := range RequiredKinds {
- _, err = dyn.Resource(schema.GroupVersionResource{
- Group: kgv.Group,
- Version: kgv.Version,
- Resource: kgv.Resource,
- }).Namespace(namespace).List(metav1.ListOptions{})
-
- if err == nil {
- return true
- }
- }
-
- log.Infof("could not find any knative type in namespace %s, last error was: %v", namespace, err)
- return false
-}
-
-// IsInstalled returns true if we are connected to a cluster with Knative installed
-//
-// This method should not be called from the operator, as it might require permissions that are not available.
-func IsInstalled(ctx context.Context, c kubernetes.Interface) (bool, error) {
- // check some Knative APIs
- for _, api := range getRequiredKnativeGroupVersions() {
- if installed, err := isInstalled(c, api); err != nil {
- return false, err
- } else if installed {
- return true, nil
- }
- }
- return false, nil
-}
-
-func isInstalled(c kubernetes.Interface, api schema.GroupVersion) (bool, error) {
- _, err := c.Discovery().ServerResourcesForGroupVersion(api.String())
- if err != nil && (k8serrors.IsNotFound(err) || kubernetesutils.IsUnknownAPIError(err)) {
- return false, nil
- } else if err != nil {
- return false, err
- }
- return true, nil
-}
-
-func getRequiredKnativeGroupVersions() []schema.GroupVersion {
- apis := make(map[schema.GroupVersion]bool)
- res := make([]schema.GroupVersion, 0)
- for _, gvk := range RequiredKinds {
- if !apis[gvk.GroupVersion()] {
- apis[gvk.GroupVersion()] = true
- res = append(res, gvk.GroupVersion())
- }
- }
- return res
-}
diff --git a/pkg/util/knative/knative.go b/pkg/util/knative/knative.go
deleted file mode 100644
index e39eb54..0000000
--- a/pkg/util/knative/knative.go
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package knative
-
-import (
- "context"
- "fmt"
- "net/url"
-
- "github.com/apache/camel-k/pkg/client"
- kubernetesutils "github.com/apache/camel-k/pkg/util/kubernetes"
- corev1 "k8s.io/api/core/v1"
- k8serrors "k8s.io/apimachinery/pkg/api/errors"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- eventing "knative.dev/eventing/pkg/apis/eventing/v1alpha1"
- messaging "knative.dev/eventing/pkg/apis/messaging/v1alpha1"
- "knative.dev/pkg/apis/duck"
- duckv1 "knative.dev/pkg/apis/duck/v1"
- serving "knative.dev/serving/pkg/apis/serving/v1"
- controller "sigs.k8s.io/controller-runtime/pkg/client"
-)
-
-// CreateSubscription ---
-func CreateSubscription(channelReference corev1.ObjectReference, serviceName string) runtime.Object {
- subs := messaging.Subscription{
- TypeMeta: metav1.TypeMeta{
- APIVersion: messaging.SchemeGroupVersion.String(),
- Kind: "Subscription",
- },
- ObjectMeta: metav1.ObjectMeta{
- Namespace: channelReference.Namespace,
- Name: channelReference.Name + "-" + serviceName,
- },
- Spec: messaging.SubscriptionSpec{
- Channel: corev1.ObjectReference{
- APIVersion: channelReference.GroupVersionKind().GroupVersion().String(),
- Kind: channelReference.Kind,
- Name: channelReference.Name,
- },
- Subscriber: &duckv1.Destination{
- Ref: &duckv1.KReference{
- APIVersion: serving.SchemeGroupVersion.String(),
- Kind: "Service",
- Name: serviceName,
- },
- },
- },
- }
-
- return &subs
-}
-
-// CreateTrigger ---
-func CreateTrigger(brokerReference corev1.ObjectReference, serviceName string, eventType string) runtime.Object {
- subs := eventing.Trigger{
- TypeMeta: metav1.TypeMeta{
- APIVersion: eventing.SchemeGroupVersion.String(),
- Kind: "Trigger",
- },
- ObjectMeta: metav1.ObjectMeta{
- Namespace: brokerReference.Namespace,
- Name: brokerReference.Name + "-" + serviceName + "-" + eventType,
- },
- Spec: eventing.TriggerSpec{
- Filter: &eventing.TriggerFilter{
- Attributes: &eventing.TriggerFilterAttributes{
- "type": eventType,
- },
- },
- Broker: brokerReference.Name,
- Subscriber: duckv1.Destination{
- Ref: &duckv1.KReference{
- APIVersion: serving.SchemeGroupVersion.String(),
- Kind: "Service",
- Name: serviceName,
- },
- },
- },
- }
- return &subs
-}
-
-// GetAddressableReference looks up the resource among all given types and returns an object reference to it
-func GetAddressableReference(ctx context.Context, c client.Client,
- possibleReferences []corev1.ObjectReference, namespace string, name string) (*corev1.ObjectReference, error) {
-
- for _, ref := range possibleReferences {
- sink := ref.DeepCopy()
- sink.Namespace = namespace
- _, err := GetSinkURI(ctx, c, sink, namespace)
- if err != nil && (k8serrors.IsNotFound(err) || kubernetesutils.IsUnknownAPIError(err)) {
- continue
- } else if err != nil {
- return nil, err
- }
-
- return sink, nil
- }
- return nil, k8serrors.NewNotFound(schema.GroupResource{}, name)
-}
-
-// GetSinkURL returns the sink as *url.URL
-func GetSinkURL(ctx context.Context, c client.Client, sink *corev1.ObjectReference, namespace string) (*url.URL, error) {
- res, err := GetSinkURI(ctx, c, sink, namespace)
- if err != nil {
- return nil, err
- }
- return url.Parse(res)
-}
-
-// GetSinkURI retrieves the sink URI from the object referenced by the given
-// ObjectReference.
-//
-// Method taken from https://github.com/knative/eventing-contrib/blob/master/pkg/controller/sinks/sinks.go
-func GetSinkURI(ctx context.Context, c client.Client, sink *corev1.ObjectReference, namespace string) (string, error) {
- if sink == nil {
- return "", fmt.Errorf("sink ref is nil")
- }
-
- u := &unstructured.Unstructured{}
- u.SetGroupVersionKind(sink.GroupVersionKind())
- err := c.Get(ctx, controller.ObjectKey{Namespace: namespace, Name: sink.Name}, u)
- if err != nil {
- return "", err
- }
-
- objIdentifier := fmt.Sprintf("\"%s/%s\" (%s)", u.GetNamespace(), u.GetName(), u.GroupVersionKind())
- // Special case v1/Service to allow it be addressable
- if u.GroupVersionKind().Kind == "Service" && u.GroupVersionKind().Group == "" && u.GroupVersionKind().Version == "v1" {
- return fmt.Sprintf("http://%s.%s.svc/", u.GetName(), u.GetNamespace()), nil
- }
-
- t := duckv1.AddressableType{}
- err = duck.FromUnstructured(u, &t)
- if err != nil {
- return "", fmt.Errorf("failed to deserialize sink %s: %v", objIdentifier, err)
- }
-
- if t.Status.Address == nil || t.Status.Address.URL == nil {
- return "", fmt.Errorf("sink %s does not contain address or URL", objIdentifier)
- }
-
- addressURL := t.Status.Address.URL
- if addressURL.Host == "" {
- return "", fmt.Errorf("sink %s contains an empty hostname", objIdentifier)
- }
- return addressURL.String(), nil
-}
diff --git a/pkg/util/knative/uri.go b/pkg/util/knative/uri.go
deleted file mode 100644
index 6536818..0000000
--- a/pkg/util/knative/uri.go
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package knative
-
-import (
- "fmt"
- "regexp"
-
- knativev1 "github.com/apache/camel-k/pkg/apis/camel/v1/knative"
- uriutils "github.com/apache/camel-k/pkg/util/uri"
- v1 "k8s.io/api/core/v1"
-)
-
-var uriRegexp = regexp.MustCompile(`^knative:[/]*(channel|endpoint|event)/([A-Za-z0-9.-]+)(?:[/?].*|$)`)
-var plainNameRegexp = regexp.MustCompile(`^[A-Za-z0-9.-]+$`)
-
-const (
- paramAPIVersion = "apiVersion"
- paramKind = "kind"
- paramBrokerName = "brokerName"
- paramBrokerAPIVersion = "brokerApiVersion"
-)
-
-// FilterURIs returns all Knative URIs of the given type from a slice
-func FilterURIs(uris []string, kind knativev1.CamelServiceType) []string {
- res := make([]string, 0)
- for _, uri := range uris {
- if isKnativeURI(kind, uri) {
- res = append(res, uri)
- }
- }
- return res
-}
-
-// NormalizeToURI produces a Knative uri of the given service type if the argument is a plain string
-func NormalizeToURI(kind knativev1.CamelServiceType, uriOrString string) string {
- if plainNameRegexp.MatchString(uriOrString) {
- return fmt.Sprintf("knative://%s/%s", string(kind), uriOrString)
- }
- return uriOrString
-}
-
-// ExtractObjectReference returns a reference to the object described in the Knative URI
-func ExtractObjectReference(uri string) (v1.ObjectReference, error) {
- if isKnativeURI(knativev1.CamelServiceTypeEvent, uri) {
- name := uriutils.GetQueryParameter(uri, paramBrokerName)
- if name == "" {
- name = "default"
- }
- apiVersion := uriutils.GetQueryParameter(uri, paramBrokerAPIVersion)
- return v1.ObjectReference{
- Name: name,
- APIVersion: apiVersion,
- Kind: "Broker",
- }, nil
- }
- name := matchOrEmpty(uriRegexp, 2, uri)
- if name == "" {
- return v1.ObjectReference{}, fmt.Errorf("cannot find name in uri %s", uri)
- }
- apiVersion := uriutils.GetQueryParameter(uri, paramAPIVersion)
- kind := uriutils.GetQueryParameter(uri, paramKind)
- return v1.ObjectReference{
- Name: name,
- APIVersion: apiVersion,
- Kind: kind,
- }, nil
-}
-
-// ExtractEventType extract the eventType from a event URI
-func ExtractEventType(uri string) string {
- return matchOrEmpty(uriRegexp, 2, uri)
-}
-
-func matchOrEmpty(reg *regexp.Regexp, index int, str string) string {
- match := reg.FindStringSubmatch(str)
- if len(match) > index {
- return match[index]
- }
- return ""
-}
-
-func isKnativeURI(kind knativev1.CamelServiceType, uri string) bool {
- match := uriRegexp.FindStringSubmatch(uri)
- if len(match) == 3 && match[1] == string(kind) {
- return true
- }
- return false
-}
diff --git a/pkg/util/knative/uri_test.go b/pkg/util/knative/uri_test.go
deleted file mode 100644
index 1ee24ee..0000000
--- a/pkg/util/knative/uri_test.go
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package knative
-
-import (
- "testing"
-
- "github.com/apache/camel-k/pkg/apis/camel/v1/knative"
- "github.com/stretchr/testify/assert"
- v1 "k8s.io/api/core/v1"
-)
-
-func TestChannelUri(t *testing.T) {
- ref, err := ExtractObjectReference("knative:endpoint/ciao")
- assert.Nil(t, err)
- assert.Equal(t, v1.ObjectReference{
- Kind: "",
- APIVersion: "",
- Name: "ciao",
- }, ref)
-
- ref, err = ExtractObjectReference("knative:endpoint/ciao?apiVersion=xxx")
- assert.Nil(t, err)
- assert.Equal(t, v1.ObjectReference{
- Kind: "",
- APIVersion: "xxx",
- Name: "ciao",
- }, ref)
-
- ref, err = ExtractObjectReference("knative:endpoint/ciao?x=y&apiVersion=xxx")
- assert.Nil(t, err)
- assert.Equal(t, v1.ObjectReference{
- Kind: "",
- APIVersion: "xxx",
- Name: "ciao",
- }, ref)
-
- ref, err = ExtractObjectReference("knative:channel/ciao2?x=y&apiVersion=eventing.knative.dev/v1&kind=KafkaChannel")
- assert.Nil(t, err)
- assert.Equal(t, v1.ObjectReference{
- Kind: "KafkaChannel",
- APIVersion: "eventing.knative.dev/v1",
- Name: "ciao2",
- }, ref)
-
- ref, err = ExtractObjectReference("knative:endpoint/ciao?aapiVersion=xxx&kind=Broker")
- assert.Nil(t, err)
- assert.Equal(t, v1.ObjectReference{
- Kind: "Broker",
- APIVersion: "",
- Name: "ciao",
- }, ref)
-
- ref, err = ExtractObjectReference("knative://endpoint/ciao?&apiVersion=serving.knative.dev/v1alpha1&kind=Service&1=1")
- assert.Nil(t, err)
- assert.Equal(t, v1.ObjectReference{
- Kind: "Service",
- APIVersion: "serving.knative.dev/v1alpha1",
- Name: "ciao",
- }, ref)
-
- ref, err = ExtractObjectReference("knative://event/chuck?&brokerApiVersion=eventing.knative.dev/v1alpha1&brokerName=broker2")
- assert.Nil(t, err)
- assert.Equal(t, v1.ObjectReference{
- APIVersion: "eventing.knative.dev/v1alpha1",
- Name: "broker2",
- Kind: "Broker",
- }, ref)
-
- ref, err = ExtractObjectReference("knative://event/chuck?&brokerApxxiVersion=eventing.knative.dev/v1alpha1&brokxerName=broker2")
- assert.Nil(t, err)
- assert.Equal(t, v1.ObjectReference{
- Name: "default",
- Kind: "Broker",
- }, ref)
-}
-
-func TestNormalizeToUri(t *testing.T) {
- assert.Equal(t, "knative://channel/name.chan", NormalizeToURI(knative.CamelServiceTypeChannel, "name.chan"))
- assert.Equal(t, "knative://event/chuck", NormalizeToURI(knative.CamelServiceTypeEvent, "chuck"))
- assert.Equal(t, "knative://endpoint/xx", NormalizeToURI(knative.CamelServiceTypeEndpoint, "xx"))
- assert.Equal(t, "direct:xxx", NormalizeToURI(knative.CamelServiceTypeChannel, "direct:xxx"))
-}
diff --git a/pkg/util/kubernetes/camel_labels.go b/pkg/util/kubernetes/camel_labels.go
deleted file mode 100644
index cc31559..0000000
--- a/pkg/util/kubernetes/camel_labels.go
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import (
- "strings"
-
- camelv1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- v1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
-)
-
-// CamelCreatorLabelPrefix --
-const (
- CamelCreatorLabelPrefix = "camel.apache.org/created.by"
-
- CamelCreatorLabelKind = CamelCreatorLabelPrefix + ".kind"
- CamelCreatorLabelName = CamelCreatorLabelPrefix + ".name"
-)
-
-// FilterCamelCreatorLabels is used to inherit the creator information among resources
-func FilterCamelCreatorLabels(source map[string]string) map[string]string {
- res := make(map[string]string)
- for k, v := range source {
- if strings.HasPrefix(k, CamelCreatorLabelPrefix) {
- res[k] = v
- }
- }
- return res
-}
-
-// MergeCamelCreatorLabels is used to inject the creator information from another set of labels
-func MergeCamelCreatorLabels(source map[string]string, target map[string]string) map[string]string {
- if target == nil {
- target = make(map[string]string)
- }
- for k, v := range FilterCamelCreatorLabels(source) {
- target[k] = v
- }
- return target
-}
-
-// GetCamelCreator returns the Camel creator object referenced by this runtime object, if present
-func GetCamelCreator(obj runtime.Object) *v1.ObjectReference {
- if m, ok := obj.(metav1.Object); ok {
- kind := m.GetLabels()[CamelCreatorLabelKind]
- name := m.GetLabels()[CamelCreatorLabelName]
- if kind != "" && name != "" {
- return &v1.ObjectReference{
- Kind: kind,
- Namespace: m.GetNamespace(),
- Name: name,
- APIVersion: camelv1.SchemeGroupVersion.String(),
- }
- }
- }
- return nil
-}
diff --git a/pkg/util/kubernetes/collection.go b/pkg/util/kubernetes/collection.go
deleted file mode 100644
index d4b6140..0000000
--- a/pkg/util/kubernetes/collection.go
+++ /dev/null
@@ -1,437 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import (
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- monitoringv1 "github.com/coreos/prometheus-operator/pkg/apis/monitoring/v1"
- routev1 "github.com/openshift/api/route/v1"
- appsv1 "k8s.io/api/apps/v1"
- "k8s.io/api/batch/v1beta1"
- corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- eventing "knative.dev/eventing/pkg/apis/eventing/v1alpha1"
- serving "knative.dev/serving/pkg/apis/serving/v1"
-)
-
-// A Collection is a container of Kubernetes resources
-type Collection struct {
- items []runtime.Object
-}
-
-// NewCollection creates a new empty collection
-func NewCollection(objects ...runtime.Object) *Collection {
- collection := Collection{
- items: make([]runtime.Object, 0, len(objects)),
- }
-
- collection.items = append(collection.items, objects...)
-
- return &collection
-}
-
-// Size returns the number of resources belonging to the collection
-func (c *Collection) Size() int {
- return len(c.items)
-}
-
-// Items returns all resources belonging to the collection
-func (c *Collection) Items() []runtime.Object {
- return c.items
-}
-
-// AsKubernetesList returns all resources wrapped in a Kubernetes list
-func (c *Collection) AsKubernetesList() *corev1.List {
- lst := corev1.List{
- TypeMeta: metav1.TypeMeta{
- Kind: "List",
- APIVersion: "v1",
- },
- Items: make([]runtime.RawExtension, 0, len(c.items)),
- }
- for _, res := range c.items {
- raw := runtime.RawExtension{
- Object: res,
- }
- lst.Items = append(lst.Items, raw)
- }
- return &lst
-}
-
-// Add adds a resource to the collection
-func (c *Collection) Add(resource runtime.Object) {
- if resource != nil {
- c.items = append(c.items, resource)
- }
-}
-
-// AddAll adds all resources to the collection
-func (c *Collection) AddAll(resource []runtime.Object) {
- c.items = append(c.items, resource...)
-}
-
-// VisitDeployment executes the visitor function on all Deployment resources
-func (c *Collection) VisitDeployment(visitor func(*appsv1.Deployment)) {
- c.Visit(func(res runtime.Object) {
- if conv, ok := res.(*appsv1.Deployment); ok {
- visitor(conv)
- }
- })
-}
-
-// VisitDeploymentE executes the visitor function on all Deployment resources
-func (c *Collection) VisitDeploymentE(visitor func(*appsv1.Deployment) error) error {
- return c.VisitE(func(res runtime.Object) error {
- if conv, ok := res.(*appsv1.Deployment); ok {
- return visitor(conv)
- }
-
- return nil
- })
-}
-
-// GetDeployment returns a Deployment that matches the given function
-func (c *Collection) GetDeployment(filter func(*appsv1.Deployment) bool) *appsv1.Deployment {
- var retValue *appsv1.Deployment
- c.VisitDeployment(func(re *appsv1.Deployment) {
- if filter(re) {
- retValue = re
- }
- })
- return retValue
-}
-
-// GetDeploymentForIntegration returns a Deployment for the given integration
-func (c *Collection) GetDeploymentForIntegration(integration *v1.Integration) *appsv1.Deployment {
- if integration == nil {
- return nil
- }
-
- return c.GetDeployment(func(d *appsv1.Deployment) bool {
- return d.ObjectMeta.Labels["camel.apache.org/integration"] == integration.Name
- })
-}
-
-// HasDeployment returns true if a deployment matching the given condition is present
-func (c *Collection) HasDeployment(filter func(*appsv1.Deployment) bool) bool {
- return c.GetDeployment(filter) != nil
-}
-
-// RemoveDeployment removes and returns a Deployment that matches the given function
-func (c *Collection) RemoveDeployment(filter func(*appsv1.Deployment) bool) *appsv1.Deployment {
- res := c.Remove(func(res runtime.Object) bool {
- if conv, ok := res.(*appsv1.Deployment); ok {
- return filter(conv)
- }
- return false
- })
- if res == nil {
- return nil
- }
- return res.(*appsv1.Deployment)
-}
-
-// VisitConfigMap executes the visitor function on all ConfigMap resources
-func (c *Collection) VisitConfigMap(visitor func(*corev1.ConfigMap)) {
- c.Visit(func(res runtime.Object) {
- if conv, ok := res.(*corev1.ConfigMap); ok {
- visitor(conv)
- }
- })
-}
-
-// GetConfigMap returns a ConfigMap that matches the given function
-func (c *Collection) GetConfigMap(filter func(*corev1.ConfigMap) bool) *corev1.ConfigMap {
- var retValue *corev1.ConfigMap
- c.VisitConfigMap(func(re *corev1.ConfigMap) {
- if filter(re) {
- retValue = re
- }
- })
- return retValue
-}
-
-// RemoveConfigMap removes and returns a ConfigMap that matches the given function
-func (c *Collection) RemoveConfigMap(filter func(*corev1.ConfigMap) bool) *corev1.ConfigMap {
- res := c.Remove(func(res runtime.Object) bool {
- if conv, ok := res.(*corev1.ConfigMap); ok {
- return filter(conv)
- }
- return false
- })
- if res == nil {
- return nil
- }
- return res.(*corev1.ConfigMap)
-}
-
-// VisitService executes the visitor function on all Service resources
-func (c *Collection) VisitService(visitor func(*corev1.Service)) {
- c.Visit(func(res runtime.Object) {
- if conv, ok := res.(*corev1.Service); ok {
- visitor(conv)
- }
- })
-}
-
-// GetService returns a Service that matches the given function
-func (c *Collection) GetService(filter func(*corev1.Service) bool) *corev1.Service {
- var retValue *corev1.Service
- c.VisitService(func(re *corev1.Service) {
- if filter(re) {
- retValue = re
- }
- })
- return retValue
-}
-
-// GetUserServiceForIntegration returns a user Service for the given integration
-func (c *Collection) GetUserServiceForIntegration(integration *v1.Integration) *corev1.Service {
- if integration == nil {
- return nil
- }
- return c.GetService(func(s *corev1.Service) bool {
- return s.ObjectMeta.Labels != nil &&
- s.ObjectMeta.Labels["camel.apache.org/integration"] == integration.Name &&
- s.ObjectMeta.Labels["camel.apache.org/service.type"] == v1.ServiceTypeUser
- })
-}
-
-// GetServiceForIntegration returns a user Service for the given integration
-func (c *Collection) GetServiceForIntegration(integration *v1.Integration) *corev1.Service {
- if integration == nil {
- return nil
- }
- return c.GetService(func(s *corev1.Service) bool {
- return s.ObjectMeta.Labels != nil && s.ObjectMeta.Labels["camel.apache.org/integration"] == integration.Name
- })
-}
-
-// GetKnativeService returns a knative Service that matches the given function
-func (c *Collection) GetKnativeService(filter func(*serving.Service) bool) *serving.Service {
- var retValue *serving.Service
- c.VisitKnativeService(func(re *serving.Service) {
- if filter(re) {
- retValue = re
- }
- })
- return retValue
-}
-
-// VisitRoute executes the visitor function on all Route resources
-func (c *Collection) VisitRoute(visitor func(*routev1.Route)) {
- c.Visit(func(res runtime.Object) {
- if conv, ok := res.(*routev1.Route); ok {
- visitor(conv)
- }
- })
-}
-
-// GetRoute returns a Route that matches the given function
-func (c *Collection) GetRoute(filter func(*routev1.Route) bool) *routev1.Route {
- var retValue *routev1.Route
- c.VisitRoute(func(re *routev1.Route) {
- if filter(re) {
- retValue = re
- }
- })
- return retValue
-}
-
-// VisitCronJob executes the visitor function on all CronJob resources
-func (c *Collection) VisitCronJob(visitor func(*v1beta1.CronJob)) {
- c.Visit(func(res runtime.Object) {
- if conv, ok := res.(*v1beta1.CronJob); ok {
- visitor(conv)
- }
- })
-}
-
-// VisitCronJobE executes the visitor function on all CronJob resources
-func (c *Collection) VisitCronJobE(visitor func(*v1beta1.CronJob) error) error {
- return c.VisitE(func(res runtime.Object) error {
- if conv, ok := res.(*v1beta1.CronJob); ok {
- return visitor(conv)
- }
-
- return nil
- })
-}
-
-// VisitKnativeService executes the visitor function on all Knative serving Service resources
-func (c *Collection) VisitKnativeService(visitor func(*serving.Service)) {
- c.Visit(func(res runtime.Object) {
- if conv, ok := res.(*serving.Service); ok {
- visitor(conv)
- }
- })
-}
-
-// VisitKnativeServiceE executes the visitor function on all Knative serving Service resources
-func (c *Collection) VisitKnativeServiceE(visitor func(*serving.Service) error) error {
- return c.VisitE(func(res runtime.Object) error {
- if conv, ok := res.(*serving.Service); ok {
- return visitor(conv)
- }
-
- return nil
- })
-}
-
-// VisitKnativeTrigger executes the visitor function on all Knative eventing Trigger resources
-func (c *Collection) VisitKnativeTrigger(visitor func(trigger *eventing.Trigger)) {
- c.Visit(func(res runtime.Object) {
- if conv, ok := res.(*eventing.Trigger); ok {
- visitor(conv)
- }
- })
-}
-
-// HasKnativeTrigger returns true if a Knative trigger respecting filter is found
-func (c *Collection) HasKnativeTrigger(filter func(trigger *eventing.Trigger) bool) bool {
- var retValue *bool
- c.VisitKnativeTrigger(func(re *eventing.Trigger) {
- if filter(re) {
- found := true
- retValue = &found
- }
- })
- return retValue != nil && *retValue
-}
-
-// GetContainer --
-func (c *Collection) GetContainer(filter func(container *corev1.Container) bool) *corev1.Container {
- var retValue *corev1.Container
-
- c.VisitContainer(func(container *corev1.Container) {
- if filter(container) {
- retValue = container
- }
- })
-
- return retValue
-}
-
-// GetContainerByName --
-func (c *Collection) GetContainerByName(name string) *corev1.Container {
- return c.GetContainer(func(c *corev1.Container) bool {
- return c.Name == name
- })
-}
-
-// VisitContainer executes the visitor function on all Containers inside deployments or other resources
-func (c *Collection) VisitContainer(visitor func(container *corev1.Container)) {
- c.VisitDeployment(func(d *appsv1.Deployment) {
- for idx := range d.Spec.Template.Spec.Containers {
- cntref := &d.Spec.Template.Spec.Containers[idx]
- visitor(cntref)
- }
- })
- c.VisitKnativeConfigurationSpec(func(cs *serving.ConfigurationSpec) {
- for id := range cs.Template.Spec.Containers {
- cntref := &cs.Template.Spec.Containers[id]
- visitor(cntref)
- }
- })
- c.VisitCronJob(func(c *v1beta1.CronJob) {
- for idx := range c.Spec.JobTemplate.Spec.Template.Spec.Containers {
- cntref := &c.Spec.JobTemplate.Spec.Template.Spec.Containers[idx]
- visitor(cntref)
- }
- })
-}
-
-// VisitPodSpec executes the visitor function on all PodSpec inside deployments or other resources
-func (c *Collection) VisitPodSpec(visitor func(container *corev1.PodSpec)) {
- c.VisitDeployment(func(d *appsv1.Deployment) {
- visitor(&d.Spec.Template.Spec)
- })
- c.VisitKnativeConfigurationSpec(func(cs *serving.ConfigurationSpec) {
- visitor(&cs.Template.Spec.PodSpec)
- })
- c.VisitCronJob(func(d *v1beta1.CronJob) {
- visitor(&d.Spec.JobTemplate.Spec.Template.Spec)
- })
-}
-
-// VisitKnativeConfigurationSpec executes the visitor function on all knative ConfigurationSpec inside serving Services
-func (c *Collection) VisitKnativeConfigurationSpec(visitor func(container *serving.ConfigurationSpec)) {
- c.VisitKnativeService(func(s *serving.Service) {
- visitor(&s.Spec.ConfigurationSpec)
- })
-}
-
-// VisitMetaObject executes the visitor function on all meta.Object resources
-func (c *Collection) VisitMetaObject(visitor func(metav1.Object)) {
- c.Visit(func(res runtime.Object) {
- if conv, ok := res.(metav1.Object); ok {
- visitor(conv)
- }
- })
-}
-
-// Visit executes the visitor function on all resources
-func (c *Collection) Visit(visitor func(runtime.Object)) {
- for _, res := range c.items {
- visitor(res)
- }
-}
-
-// VisitE executes the visitor function on all resources breaking if the visitor function
-// returns an error
-func (c *Collection) VisitE(visitor func(runtime.Object) error) error {
- for _, res := range c.items {
- if err := visitor(res); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// Remove removes the given element from the collection and returns it
-func (c *Collection) Remove(selector func(runtime.Object) bool) runtime.Object {
- for idx, res := range c.items {
- if selector(res) {
- c.items = append(c.items[0:idx], c.items[idx+1:]...)
- return res
- }
- }
- return nil
-}
-
-// VisitServiceMonitor ---
-func (c *Collection) VisitServiceMonitor(visitor func(*monitoringv1.ServiceMonitor)) {
- c.Visit(func(res runtime.Object) {
- if conv, ok := res.(*monitoringv1.ServiceMonitor); ok {
- visitor(conv)
- }
- })
-}
-
-// GetServiceMonitor ---
-func (c *Collection) GetServiceMonitor(filter func(*monitoringv1.ServiceMonitor) bool) *monitoringv1.ServiceMonitor {
- var retValue *monitoringv1.ServiceMonitor
- c.VisitServiceMonitor(func(serviceMonitor *monitoringv1.ServiceMonitor) {
- if filter(serviceMonitor) {
- retValue = serviceMonitor
- }
- })
- return retValue
-}
diff --git a/pkg/util/kubernetes/customclient/customclient.go b/pkg/util/kubernetes/customclient/customclient.go
deleted file mode 100644
index d3810be..0000000
--- a/pkg/util/kubernetes/customclient/customclient.go
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package customclient
-
-import (
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/client-go/dynamic"
- "k8s.io/client-go/kubernetes"
- "k8s.io/client-go/rest"
- "sigs.k8s.io/controller-runtime/pkg/client/config"
-)
-
-// GetClientFor returns a RESTClient for the given group and version
-func GetClientFor(c kubernetes.Interface, group string, version string) (*rest.RESTClient, error) {
- inConfig, err := config.GetConfig()
- if err != nil {
- return nil, err
- }
- conf := rest.CopyConfig(inConfig)
- conf.GroupVersion = &schema.GroupVersion{
- Group: group,
- Version: version,
- }
- conf.APIPath = "/apis"
- conf.AcceptContentTypes = "application/json"
- conf.ContentType = "application/json"
-
- // this gets used for discovery and error handling types
- conf.NegotiatedSerializer = basicNegotiatedSerializer{}
- if conf.UserAgent == "" {
- conf.UserAgent = rest.DefaultKubernetesUserAgent()
- }
-
- return rest.RESTClientFor(conf)
-}
-
-// GetDynamicClientFor returns a dynamic client for a given kind
-func GetDynamicClientFor(group string, version string, kind string, namespace string) (dynamic.ResourceInterface, error) {
- conf, err := config.GetConfig()
- if err != nil {
- return nil, err
- }
- dynamicClient, err := dynamic.NewForConfig(conf)
- if err != nil {
- return nil, err
- }
- return dynamicClient.Resource(schema.GroupVersionResource{
- Group: group,
- Version: version,
- Resource: kind,
- }).Namespace(namespace), nil
-}
-
-// GetDefaultDynamicClientFor returns a dynamic client for a given kind
-func GetDefaultDynamicClientFor(kind string, namespace string) (dynamic.ResourceInterface, error) {
- conf, err := config.GetConfig()
- if err != nil {
- return nil, err
- }
- dynamicClient, err := dynamic.NewForConfig(conf)
- if err != nil {
- return nil, err
- }
- return dynamicClient.Resource(schema.GroupVersionResource{
- Group: v1.SchemeGroupVersion.Group,
- Version: v1.SchemeGroupVersion.Version,
- Resource: kind,
- }).Namespace(namespace), nil
-}
diff --git a/pkg/util/kubernetes/customclient/scheme.go b/pkg/util/kubernetes/customclient/scheme.go
deleted file mode 100644
index ba261e8..0000000
--- a/pkg/util/kubernetes/customclient/scheme.go
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package customclient
-
-import (
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/apimachinery/pkg/runtime/serializer/json"
- "k8s.io/apimachinery/pkg/runtime/serializer/versioning"
-)
-
-var watchScheme = runtime.NewScheme()
-var basicScheme = runtime.NewScheme()
-var deleteScheme = runtime.NewScheme()
-var parameterScheme = runtime.NewScheme()
-var versionV1 = schema.GroupVersion{Version: "v1"}
-
-func init() {
- metav1.AddToGroupVersion(watchScheme, versionV1)
- metav1.AddToGroupVersion(basicScheme, versionV1)
- metav1.AddToGroupVersion(parameterScheme, versionV1)
- metav1.AddToGroupVersion(deleteScheme, versionV1)
-}
-
-// basicNegotiatedSerializer is used to handle discovery and error handling serialization
-type basicNegotiatedSerializer struct{}
-
-func (s basicNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo {
- return []runtime.SerializerInfo{
- {
- MediaType: "application/json",
- EncodesAsText: true,
- Serializer: json.NewSerializer(json.DefaultMetaFactory, basicScheme, basicScheme, false),
- PrettySerializer: json.NewSerializer(json.DefaultMetaFactory, basicScheme, basicScheme, true),
- StreamSerializer: &runtime.StreamSerializerInfo{
- EncodesAsText: true,
- Serializer: json.NewSerializer(json.DefaultMetaFactory, basicScheme, basicScheme, false),
- Framer: json.Framer,
- },
- },
- }
-}
-
-func (s basicNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
- return versioning.NewDefaultingCodecForScheme(watchScheme, encoder, nil, gv, nil)
-}
-
-func (s basicNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {
- return versioning.NewDefaultingCodecForScheme(watchScheme, nil, decoder, nil, gv)
-}
diff --git a/pkg/util/kubernetes/errors.go b/pkg/util/kubernetes/errors.go
deleted file mode 100644
index dd86544..0000000
--- a/pkg/util/kubernetes/errors.go
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import "strings"
-
-// IsUnknownAPIError checks if the given error is due to some missing APIs in the cluster.
-// Apparently there's no such method in Kubernetes Go API.
-func IsUnknownAPIError(err error) bool {
- return err != nil && strings.HasPrefix(err.Error(), "no matches for kind")
-}
diff --git a/pkg/util/kubernetes/loader.go b/pkg/util/kubernetes/loader.go
deleted file mode 100644
index aba9700..0000000
--- a/pkg/util/kubernetes/loader.go
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import (
- "encoding/json"
- "fmt"
-
- "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/runtime/serializer"
- "k8s.io/apimachinery/pkg/util/yaml"
-)
-
-// LoadResourceFromYaml loads a k8s resource from a yaml definition
-func LoadResourceFromYaml(scheme *runtime.Scheme, data string) (runtime.Object, error) {
- source := []byte(data)
- jsonSource, err := yaml.ToJSON(source)
- if err != nil {
- return nil, err
- }
- u := unstructured.Unstructured{}
- err = u.UnmarshalJSON(jsonSource)
- if err != nil {
- return nil, err
- }
- return RuntimeObjectFromUnstructured(scheme, &u)
-}
-
-// LoadRawResourceFromYaml loads a k8s resource from a yaml definition without making assumptions on the underlying type
-func LoadRawResourceFromYaml(data string) (runtime.Object, error) {
- source := []byte(data)
- jsonSource, err := yaml.ToJSON(source)
- if err != nil {
- return nil, err
- }
- var objmap map[string]interface{}
- if err = json.Unmarshal(jsonSource, &objmap); err != nil {
- return nil, err
- }
- return &unstructured.Unstructured{
- Object: objmap,
- }, nil
-}
-
-// RuntimeObjectFromUnstructured converts an unstructured to a runtime object
-func RuntimeObjectFromUnstructured(scheme *runtime.Scheme, u *unstructured.Unstructured) (runtime.Object, error) {
- gvk := u.GroupVersionKind()
- codecs := serializer.NewCodecFactory(scheme)
- decoder := codecs.UniversalDecoder(gvk.GroupVersion())
-
- b, err := u.MarshalJSON()
- if err != nil {
- return nil, fmt.Errorf("error running MarshalJSON on unstructured object: %v", err)
- }
- ro, _, err := decoder.Decode(b, &gvk, nil)
- if err != nil {
- return nil, fmt.Errorf("failed to decode json data with gvk(%v): %v", gvk.String(), err)
- }
- return ro, nil
-}
diff --git a/pkg/util/kubernetes/log/annotation_scraper.go b/pkg/util/kubernetes/log/annotation_scraper.go
deleted file mode 100644
index adc5f1a..0000000
--- a/pkg/util/kubernetes/log/annotation_scraper.go
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package log
-
-import (
- "bufio"
- "context"
- "io"
- "strconv"
- "sync"
- "sync/atomic"
- "time"
-
- klog "github.com/apache/camel-k/pkg/util/log"
- corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-
- "k8s.io/client-go/kubernetes"
-)
-
-// SelectorScraper scrapes all pods with a given selector
-type SelectorScraper struct {
- client kubernetes.Interface
- namespace string
- defaultContainerName string
- labelSelector string
- podScrapers sync.Map
- counter uint64
- L klog.Logger
-}
-
-// NewSelectorScraper creates a new SelectorScraper
-func NewSelectorScraper(client kubernetes.Interface, namespace string, defaultContainerName string, labelSelector string) *SelectorScraper {
- return &SelectorScraper{
- client: client,
- namespace: namespace,
- defaultContainerName: defaultContainerName,
- labelSelector: labelSelector,
- L: klog.WithName("scraper").WithName("label").WithValues("selector", labelSelector),
- }
-}
-
-// Start returns a reader that streams the log of all selected pods
-func (s *SelectorScraper) Start(ctx context.Context) *bufio.Reader {
- pipeIn, pipeOut := io.Pipe()
- bufPipeIn := bufio.NewReader(pipeIn)
- bufPipeOut := bufio.NewWriter(pipeOut)
- closeFun := func() error {
- bufPipeOut.Flush()
- return pipeOut.Close()
- }
- go s.periodicSynchronize(ctx, bufPipeOut, closeFun)
- return bufPipeIn
-}
-
-func (s *SelectorScraper) periodicSynchronize(ctx context.Context, out *bufio.Writer, clientCloser func() error) {
- err := s.synchronize(ctx, out)
- if err != nil {
- s.L.Info("Could not synchronize log")
- }
- select {
- case <-ctx.Done():
- // cleanup
- s.podScrapers.Range(func(_, v interface{}) bool {
- if canc, isCanc := v.(context.CancelFunc); isCanc {
- canc()
- }
-
- return true
- })
- if err := clientCloser(); err != nil {
- s.L.Error(err, "Unable to close the client")
- }
- case <-time.After(2 * time.Second):
- go s.periodicSynchronize(ctx, out, clientCloser)
- }
-}
-
-func (s *SelectorScraper) synchronize(ctx context.Context, out *bufio.Writer) error {
- list, err := s.listPods()
- if err != nil {
- return err
- }
-
- present := make(map[string]bool)
- for _, pod := range list.Items {
- present[pod.Name] = true
- if _, ok := s.podScrapers.Load(pod.Name); !ok {
- s.addPodScraper(ctx, pod.Name, out)
- }
- }
-
- toBeRemoved := make(map[string]bool)
- s.podScrapers.Range(func(k, _ interface{}) bool {
- if str, isStr := k.(string); isStr {
- if _, ok := present[str]; !ok {
- toBeRemoved[str] = true
- }
- }
-
- return true
- })
-
- for podName := range toBeRemoved {
- if scr, ok := s.podScrapers.Load(podName); ok {
- if canc, ok2 := scr.(context.CancelFunc); ok2 {
- canc()
- s.podScrapers.Delete(podName)
- }
- }
- }
- return nil
-}
-
-func (s *SelectorScraper) addPodScraper(ctx context.Context, podName string, out *bufio.Writer) {
- podScraper := NewPodScraper(s.client, s.namespace, podName, s.defaultContainerName)
- podCtx, podCancel := context.WithCancel(ctx)
- id := atomic.AddUint64(&s.counter, 1)
- prefix := "[" + strconv.FormatUint(id, 10) + "] "
- podReader := podScraper.Start(podCtx)
- s.podScrapers.Store(podName, podCancel)
- go func() {
- defer podCancel()
-
- if _, err := out.WriteString(prefix + "Monitoring pod " + podName); err != nil {
- s.L.Error(err, "Cannot write to output")
- return
- }
- for {
- str, err := podReader.ReadString('\n')
- if err == io.EOF {
- return
- } else if err != nil {
- s.L.Error(err, "Cannot read from pod stream")
- return
- }
- if _, err := out.WriteString(prefix + str); err != nil {
- s.L.Error(err, "Cannot write to output")
- return
- }
- out.Flush()
- if podCtx.Err() != nil {
- return
- }
- }
- }()
-}
-
-func (s *SelectorScraper) listPods() (*corev1.PodList, error) {
- list, err := s.client.CoreV1().Pods(s.namespace).List(metav1.ListOptions{
- LabelSelector: s.labelSelector,
- })
- if err != nil {
- return nil, err
- }
-
- return list, nil
-}
diff --git a/pkg/util/kubernetes/log/pod_scraper.go b/pkg/util/kubernetes/log/pod_scraper.go
deleted file mode 100644
index 1d1a583..0000000
--- a/pkg/util/kubernetes/log/pod_scraper.go
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package log
-
-import (
- "bufio"
- "context"
- "io"
- "time"
-
- klog "github.com/apache/camel-k/pkg/util/log"
- "github.com/pkg/errors"
- corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/util/json"
- "k8s.io/apimachinery/pkg/watch"
- "k8s.io/client-go/kubernetes"
-)
-
-var commonUserContainerNames = map[string]bool{
- // Convention used in Knative and Istio
- "user-container": true,
-}
-
-// PodScraper scrapes logs of a specific pod
-type PodScraper struct {
- namespace string
- podName string
- defaultContainerName string
- client kubernetes.Interface
- L klog.Logger
-}
-
-// NewPodScraper creates a new pod scraper
-func NewPodScraper(c kubernetes.Interface, namespace string, podName string, defaultContainerName string) *PodScraper {
- return &PodScraper{
- namespace: namespace,
- podName: podName,
- defaultContainerName: defaultContainerName,
- client: c,
- L: klog.WithName("scraper").WithName("pod").WithValues("name", podName),
- }
-}
-
-// Start returns a reader that streams the pod logs
-func (s *PodScraper) Start(ctx context.Context) *bufio.Reader {
- pipeIn, pipeOut := io.Pipe()
- bufPipeIn := bufio.NewReader(pipeIn)
- bufPipeOut := bufio.NewWriter(pipeOut)
- closeFun := func() error {
- bufPipeOut.Flush()
- return pipeOut.Close()
- }
- go s.doScrape(ctx, bufPipeOut, closeFun)
- return bufPipeIn
-}
-
-func (s *PodScraper) doScrape(ctx context.Context, out *bufio.Writer, clientCloser func() error) {
- containerName, err := s.waitForPodRunning(ctx, s.namespace, s.podName, s.defaultContainerName)
- if err != nil {
- s.handleAndRestart(ctx, err, 5*time.Second, out, clientCloser)
- return
- }
- logOptions := corev1.PodLogOptions{
- Follow: true,
- Container: containerName,
- }
- byteReader, err := s.client.CoreV1().Pods(s.namespace).GetLogs(s.podName, &logOptions).Context(ctx).Stream()
- if err != nil {
- s.handleAndRestart(ctx, err, 5*time.Second, out, clientCloser)
- return
- }
-
- reader := bufio.NewReader(byteReader)
- for {
- data, err := reader.ReadBytes('\n')
- if err == io.EOF {
- return
- }
- if err != nil {
- break
- }
- _, err = out.Write(data)
- if err != nil {
- break
- }
- out.Flush()
- }
-
- s.handleAndRestart(ctx, err, 5*time.Second, out, clientCloser)
-}
-
-func (s *PodScraper) handleAndRestart(ctx context.Context, err error, wait time.Duration, out *bufio.Writer, clientCloser func() error) {
- if err != nil {
- s.L.Error(err, "error caught during log scraping")
- }
-
- if ctx.Err() != nil {
- s.L.Debug("Pod will no longer be monitored")
- if err := clientCloser(); err != nil {
- s.L.Error(err, "Unable to close the client")
- }
- return
- }
-
- s.L.Debugf("Retrying to scrape pod logs in %f seconds...", wait.Seconds())
- select {
- case <-time.After(wait):
- break
- case <-ctx.Done():
- if err := clientCloser(); err != nil {
- s.L.Error(err, "Unable to close the client")
- }
- return
- }
-
- s.doScrape(ctx, out, clientCloser)
-}
-
-// waitForPodRunning waits for a given pod to reach the running state.
-// It may return the internal container to watch if present
-func (s *PodScraper) waitForPodRunning(ctx context.Context, namespace string, podName string, defaultContainerName string) (string, error) {
- pod := corev1.Pod{
- TypeMeta: metav1.TypeMeta{
- Kind: "Pod",
- APIVersion: corev1.SchemeGroupVersion.String(),
- },
- ObjectMeta: metav1.ObjectMeta{
- Name: podName,
- Namespace: namespace,
- },
- }
- podClient := s.client.CoreV1().Pods(pod.Namespace)
- watcher, err := podClient.Watch(metav1.ListOptions{
- FieldSelector: "metadata.name=" + pod.Name,
- })
- if err != nil {
- return "", err
- }
- events := watcher.ResultChan()
- for {
- select {
- case <-ctx.Done():
- return "", ctx.Err()
- case e, ok := <-events:
- if !ok {
- return "", errors.New("event channel closed")
- }
-
- if e.Object != nil {
- var recvPod *corev1.Pod
- if runtimeUnstructured, ok := e.Object.(runtime.Unstructured); ok {
- unstr := unstructured.Unstructured{
- Object: runtimeUnstructured.UnstructuredContent(),
- }
- jsondata, err := unstr.MarshalJSON()
- if err != nil {
- return "", err
- }
- recvPod := pod.DeepCopy()
- if err := json.Unmarshal(jsondata, recvPod); err != nil {
- return "", err
- }
- } else if gotPod, ok := e.Object.(*corev1.Pod); ok {
- recvPod = gotPod
- }
-
- if recvPod != nil && recvPod.Status.Phase == corev1.PodRunning {
- return s.chooseContainer(recvPod, defaultContainerName), nil
- }
- } else if e.Type == watch.Deleted || e.Type == watch.Error {
- return "", errors.New("unable to watch pod " + s.podName)
- }
- case <-time.After(30 * time.Second):
- return "", errors.New("no state change after 30 seconds for pod " + s.podName)
- }
- }
-}
-
-func (s *PodScraper) chooseContainer(p *corev1.Pod, defaultContainerName string) string {
- if p != nil {
- if len(p.Spec.Containers) == 1 {
- // Let Kubernetes auto-detect
- return ""
- }
- // Fallback to first container name
- containerNameFound := p.Spec.Containers[0].Name
- for _, c := range p.Spec.Containers {
- if _, ok := commonUserContainerNames[c.Name]; ok {
- return c.Name
- } else if c.Name == defaultContainerName {
- containerNameFound = defaultContainerName
- }
- }
- return containerNameFound
- }
- return ""
-}
diff --git a/pkg/util/kubernetes/log/util.go b/pkg/util/kubernetes/log/util.go
deleted file mode 100644
index bd72a94..0000000
--- a/pkg/util/kubernetes/log/util.go
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package log
-
-import (
- "context"
- "fmt"
- "io"
- "io/ioutil"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
-
- "k8s.io/client-go/kubernetes"
-)
-
-// Print prints integrations logs to the stdout
-func Print(ctx context.Context, client kubernetes.Interface, integration *v1.Integration, out io.Writer) error {
- scraper := NewSelectorScraper(client, integration.Namespace, integration.Name, "camel.apache.org/integration="+integration.Name)
- reader := scraper.Start(ctx)
-
- if _, err := io.Copy(out, ioutil.NopCloser(reader)); err != nil {
- fmt.Println(err.Error())
- }
-
- return nil
-}
diff --git a/pkg/util/kubernetes/permission.go b/pkg/util/kubernetes/permission.go
deleted file mode 100644
index e72be7d..0000000
--- a/pkg/util/kubernetes/permission.go
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import (
- "github.com/apache/camel-k/pkg/client"
- authorizationv1 "k8s.io/api/authorization/v1"
- k8serrors "k8s.io/apimachinery/pkg/api/errors"
-)
-
-// CheckPermission can be used to check if the current user/service-account is allowed to execute a given operation
-// in the cluster.
-// E.g. checkPermission(client, olmv1alpha1.GroupName, "clusterserviceversions", namespace, "camel-k", "get")
-//
-// nolint:unparam
-func CheckPermission(client client.Client, group, resource, namespace, name, verb string) (bool, error) {
- sarReview := &authorizationv1.SelfSubjectAccessReview{
- Spec: authorizationv1.SelfSubjectAccessReviewSpec{
- ResourceAttributes: &authorizationv1.ResourceAttributes{
- Group: group,
- Resource: resource,
- Namespace: namespace,
- Name: name,
- Verb: verb,
- },
- },
- }
-
- sar, err := client.AuthorizationV1().SelfSubjectAccessReviews().Create(sarReview)
- if err != nil {
- if k8serrors.IsForbidden(err) {
- return false, nil
- }
- return false, err
- } else if !sar.Status.Allowed {
- return false, nil
- }
- return true, nil
-}
diff --git a/pkg/util/kubernetes/replace.go b/pkg/util/kubernetes/replace.go
deleted file mode 100644
index c0c417a..0000000
--- a/pkg/util/kubernetes/replace.go
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import (
- "context"
-
- "github.com/apache/camel-k/pkg/client"
- routev1 "github.com/openshift/api/route/v1"
- "github.com/pkg/errors"
- corev1 "k8s.io/api/core/v1"
- k8serrors "k8s.io/apimachinery/pkg/api/errors"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- messaging "knative.dev/eventing/pkg/apis/messaging/v1alpha1"
- serving "knative.dev/serving/pkg/apis/serving/v1"
- k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
-)
-
-// ReplaceResources allows to completely replace a list of resources on Kubernetes, taking care of immutable fields and resource versions
-func ReplaceResources(ctx context.Context, c client.Client, objects []runtime.Object) error {
- for _, object := range objects {
- err := ReplaceResource(ctx, c, object)
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-// ReplaceResource allows to completely replace a resource on Kubernetes, taking care of immutable fields and resource versions
-func ReplaceResource(ctx context.Context, c client.Client, res runtime.Object) error {
- err := c.Create(ctx, res)
- if err != nil && k8serrors.IsAlreadyExists(err) {
- existing := res.DeepCopyObject()
- var key k8sclient.ObjectKey
- key, err = k8sclient.ObjectKeyFromObject(existing)
- if err != nil {
- return err
- }
- err = c.Get(ctx, key, existing)
- if err != nil {
- return err
- }
- mapRequiredMeta(existing, res)
- mapRequiredServiceData(existing, res)
- mapRequiredRouteData(existing, res)
- mapRequiredKnativeData(existing, res)
- mapRequiredKnativeServiceV1Beta1Data(existing, res)
- mapRequiredKnativeServiceV1Data(existing, res)
- err = c.Update(ctx, res)
- }
- if err != nil {
- return errors.Wrap(err, "could not create or replace "+findResourceDetails(res))
- }
- return nil
-}
-
-func mapRequiredMeta(from runtime.Object, to runtime.Object) {
- if fromC, ok := from.(metav1.Object); ok {
- if toC, ok := to.(metav1.Object); ok {
- toC.SetResourceVersion(fromC.GetResourceVersion())
- }
- }
-}
-
-func mapRequiredServiceData(from runtime.Object, to runtime.Object) {
- if fromC, ok := from.(*corev1.Service); ok {
- if toC, ok := to.(*corev1.Service); ok {
- toC.Spec.ClusterIP = fromC.Spec.ClusterIP
- }
- }
-}
-
-func mapRequiredRouteData(from runtime.Object, to runtime.Object) {
- if fromC, ok := from.(*routev1.Route); ok {
- if toC, ok := to.(*routev1.Route); ok {
- toC.Spec.Host = fromC.Spec.Host
- }
- }
-}
-
-func mapRequiredKnativeData(from runtime.Object, to runtime.Object) {
- if fromC, ok := from.(*messaging.Subscription); ok {
- if toC, ok := to.(*messaging.Subscription); ok {
- toC.Spec.DeprecatedGeneration = fromC.Spec.DeprecatedGeneration
- }
- }
-}
-
-func mapRequiredKnativeServiceV1Beta1Data(from runtime.Object, to runtime.Object) {
- if fromC, ok := from.(*serving.Service); ok {
- if toC, ok := to.(*serving.Service); ok {
- if toC.ObjectMeta.Annotations == nil {
- toC.ObjectMeta.Annotations = make(map[string]string)
- }
- if v, present := fromC.ObjectMeta.Annotations["serving.knative.dev/creator"]; present {
- toC.ObjectMeta.Annotations["serving.knative.dev/creator"] = v
- }
- if v, present := fromC.ObjectMeta.Annotations["serving.knative.dev/lastModifier"]; present {
- toC.ObjectMeta.Annotations["serving.knative.dev/lastModifier"] = v
- }
- }
- }
-}
-
-func mapRequiredKnativeServiceV1Data(from runtime.Object, to runtime.Object) {
- if fromC, ok := from.(*serving.Service); ok {
- if toC, ok := to.(*serving.Service); ok {
- if toC.ObjectMeta.Annotations == nil {
- toC.ObjectMeta.Annotations = make(map[string]string)
- }
- if v, present := fromC.ObjectMeta.Annotations["serving.knative.dev/creator"]; present {
- toC.ObjectMeta.Annotations["serving.knative.dev/creator"] = v
- }
- if v, present := fromC.ObjectMeta.Annotations["serving.knative.dev/lastModifier"]; present {
- toC.ObjectMeta.Annotations["serving.knative.dev/lastModifier"] = v
- }
- }
- }
-}
-
-func findResourceDetails(res runtime.Object) string {
- if res == nil {
- return "nil resource"
- }
- if meta, ok := res.(metav1.Object); ok {
- name := meta.GetName()
- if ty, ok := res.(metav1.Type); ok {
- return ty.GetKind() + " " + name
- }
- return "resource " + name
- }
- return "unnamed resource"
-}
diff --git a/pkg/util/kubernetes/resolver.go b/pkg/util/kubernetes/resolver.go
deleted file mode 100644
index fbb3eff..0000000
--- a/pkg/util/kubernetes/resolver.go
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import (
- "context"
- "fmt"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
-
- corev1 "k8s.io/api/core/v1"
- controller "sigs.k8s.io/controller-runtime/pkg/client"
-)
-
-// ResolveSources --
-func ResolveSources(elements []v1.SourceSpec, mapLookup func(string) (*corev1.ConfigMap, error)) ([]v1.SourceSpec, error) {
- for i := 0; i < len(elements); i++ {
- r := &elements[i]
-
- if err := Resolve(&r.DataSpec, mapLookup); err != nil {
- return nil, err
- }
- }
-
- return elements, nil
-}
-
-// ResolveResource --
-func ResolveResource(elements []v1.ResourceSpec, mapLookup func(string) (*corev1.ConfigMap, error)) ([]v1.ResourceSpec, error) {
- for i := 0; i < len(elements); i++ {
- r := &elements[i]
-
- if err := Resolve(&r.DataSpec, mapLookup); err != nil {
- return nil, err
- }
- }
-
- return elements, nil
-}
-
-// Resolve --
-func Resolve(data *v1.DataSpec, mapLookup func(string) (*corev1.ConfigMap, error)) error {
- // if it is a reference, get the content from the
- // referenced ConfigMap
- if data.ContentRef != "" {
- //look up the ConfigMap from the kubernetes cluster
- cm, err := mapLookup(data.ContentRef)
- if err != nil {
- return err
- }
-
- if cm == nil {
- return fmt.Errorf("unable to find a ConfigMap with name: %s ", data.ContentRef)
- }
-
- //
- // Replace ref source content with real content
- //
- data.Content = cm.Data["content"]
- data.ContentRef = ""
- }
-
- return nil
-}
-
-// ResolveIntegrationSources --
-func ResolveIntegrationSources(
- context context.Context,
- client controller.Reader,
- integration *v1.Integration,
- resources *Collection) ([]v1.SourceSpec, error) {
-
- if integration == nil {
- return nil, nil
- }
-
- return ResolveSources(integration.Sources(), func(name string) (*corev1.ConfigMap, error) {
- // the config map could be part of the resources created
- // by traits
- cm := resources.GetConfigMap(func(m *corev1.ConfigMap) bool {
- return m.Name == name
- })
-
- if cm != nil {
- return cm, nil
- }
-
- return GetConfigMap(context, client, name, integration.Namespace)
- })
-}
-
-// ResolveIntegrationResources --
-// nolint: lll
-func ResolveIntegrationResources(
- context context.Context,
- client controller.Reader,
- integration *v1.Integration,
- resources *Collection) ([]v1.ResourceSpec, error) {
-
- if integration == nil {
- return nil, nil
- }
-
- return ResolveResource(integration.Spec.Resources, func(name string) (*corev1.ConfigMap, error) {
- // the config map could be part of the resources created
- // by traits
- cm := resources.GetConfigMap(func(m *corev1.ConfigMap) bool {
- return m.Name == name
- })
-
- if cm != nil {
- return cm, nil
- }
-
- return GetConfigMap(context, client, name, integration.Namespace)
- })
-}
diff --git a/pkg/util/kubernetes/sanitize.go b/pkg/util/kubernetes/sanitize.go
deleted file mode 100644
index 1ed8026..0000000
--- a/pkg/util/kubernetes/sanitize.go
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import (
- "path"
- "regexp"
- "strings"
- "unicode"
-
- scase "github.com/stoewer/go-strcase"
-)
-
-var disallowedChars = regexp.MustCompile(`[^a-z0-9-]`)
-
-// SanitizeName sanitizes the given name to be compatible with k8s
-func SanitizeName(name string) string {
- name = path.Base(name)
- name = strings.Split(name, ".")[0]
- name = scase.KebabCase(name)
- name = strings.ToLower(name)
- name = disallowedChars.ReplaceAllString(name, "")
- name = strings.TrimFunc(name, isDisallowedStartEndChar)
- return name
-}
-
-// SanitizeLabel sanitizes the given name to be compatible with k8s
-func SanitizeLabel(name string) string {
- name = strings.ToLower(name)
- name = disallowedChars.ReplaceAllString(name, "")
- name = strings.TrimFunc(name, isDisallowedStartEndChar)
- return name
-}
-
-func isDisallowedStartEndChar(rune rune) bool {
- return !unicode.IsLetter(rune) && !unicode.IsNumber(rune)
-}
diff --git a/pkg/util/kubernetes/sanitize_test.go b/pkg/util/kubernetes/sanitize_test.go
deleted file mode 100644
index 31b422e..0000000
--- a/pkg/util/kubernetes/sanitize_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import (
- "testing"
-)
-
-func TestSanitizeName(t *testing.T) {
- cases := []map[string]string{
- {"input": "./abc.java", "expect": "abc"},
- {"input": "../../abc.java", "expect": "abc"},
- {"input": "/path/to/abc.js", "expect": "abc"},
- {"input": "abc.xml", "expect": "abc"},
- {"input": "./path/to/abc.kts", "expect": "abc"},
- {"input": "fooToBar.groovy", "expect": "foo-to-bar"},
- {"input": "foo-to-bar", "expect": "foo-to-bar"},
- {"input": "http://foo.bar.com/cheese/wine/beer/abc.java", "expect": "abc"},
- {"input": "http://foo.bar.com/cheese", "expect": "cheese"},
- {"input": "http://foo.bar.com", "expect": "foo"},
- {"input": "-foo-bar-", "expect": "foo-bar"},
- {"input": "1foo-bar2", "expect": "1foo-bar2"},
- {"input": "foo-bar-1", "expect": "foo-bar-1"},
- }
-
- for _, c := range cases {
- if name := SanitizeName(c["input"]); name != c["expect"] {
- t.Errorf("result of %s should be %s, instead of %s", c["input"], c["expect"], name)
- }
- }
-}
diff --git a/pkg/util/kubernetes/util.go b/pkg/util/kubernetes/util.go
deleted file mode 100644
index 9fd960a..0000000
--- a/pkg/util/kubernetes/util.go
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import (
- "context"
- "fmt"
-
- corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/util/json"
- k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/client"
- yaml2 "gopkg.in/yaml.v2"
-)
-
-// ToJSON --
-func ToJSON(value runtime.Object) ([]byte, error) {
- return json.Marshal(value)
-}
-
-// ToYAML --
-func ToYAML(value runtime.Object) ([]byte, error) {
- data, err := ToJSON(value)
- if err != nil {
- return nil, err
- }
-
- return JSONToYAML(data)
-}
-
-// JSONToYAML --
-func JSONToYAML(src []byte) ([]byte, error) {
- jsondata := map[string]interface{}{}
- err := json.Unmarshal(src, &jsondata)
- if err != nil {
- return nil, fmt.Errorf("error unmarshalling json: %v", err)
- }
- yamldata, err := yaml2.Marshal(&jsondata)
- if err != nil {
- return nil, fmt.Errorf("error marshalling to yaml: %v", err)
- }
-
- return yamldata, nil
-}
-
-// GetConfigMap --
-func GetConfigMap(context context.Context, client k8sclient.Reader, name string, namespace string) (*corev1.ConfigMap, error) {
- key := k8sclient.ObjectKey{
- Name: name,
- Namespace: namespace,
- }
-
- answer := corev1.ConfigMap{
- TypeMeta: metav1.TypeMeta{
- Kind: "ConfigMap",
- APIVersion: "v1",
- },
- ObjectMeta: metav1.ObjectMeta{
- Name: name,
- Namespace: namespace,
- },
- }
-
- if err := client.Get(context, key, &answer); err != nil {
- return nil, err
- }
-
- return &answer, nil
-}
-
-// GetSecret --
-func GetSecret(context context.Context, client k8sclient.Reader, name string, namespace string) (*corev1.Secret, error) {
- key := k8sclient.ObjectKey{
- Name: name,
- Namespace: namespace,
- }
-
- answer := corev1.Secret{
- TypeMeta: metav1.TypeMeta{
- Kind: "Secret",
- APIVersion: "v1",
- },
- ObjectMeta: metav1.ObjectMeta{
- Name: name,
- Namespace: namespace,
- },
- }
-
- if err := client.Get(context, key, &answer); err != nil {
- return nil, err
- }
-
- return &answer, nil
-}
-
-// GetIntegrationPlatform --
-func GetIntegrationPlatform(context context.Context, client k8sclient.Reader, name string, namespace string) (*v1.IntegrationPlatform, error) {
- key := k8sclient.ObjectKey{
- Name: name,
- Namespace: namespace,
- }
-
- answer := v1.NewIntegrationPlatform(namespace, name)
-
- if err := client.Get(context, key, &answer); err != nil {
- return nil, err
- }
-
- return &answer, nil
-}
-
-// GetIntegrationKit --
-func GetIntegrationKit(context context.Context, client k8sclient.Reader, name string, namespace string) (*v1.IntegrationKit, error) {
- key := k8sclient.ObjectKey{
- Name: name,
- Namespace: namespace,
- }
-
- answer := v1.NewIntegrationKit(namespace, name)
-
- if err := client.Get(context, key, &answer); err != nil {
- return nil, err
- }
-
- return &answer, nil
-}
-
-// GetIntegration --
-func GetIntegration(context context.Context, client k8sclient.Reader, name string, namespace string) (*v1.Integration, error) {
- key := k8sclient.ObjectKey{
- Name: name,
- Namespace: namespace,
- }
-
- answer := v1.NewIntegration(namespace, name)
-
- if err := client.Get(context, key, &answer); err != nil {
- return nil, err
- }
-
- return &answer, nil
-}
-
-// GetBuild --
-func GetBuild(context context.Context, client client.Client, name string, namespace string) (*v1.Build, error) {
- key := k8sclient.ObjectKey{
- Name: name,
- Namespace: namespace,
- }
-
- answer := v1.NewBuild(namespace, name)
-
- if err := client.Get(context, key, &answer); err != nil {
- return nil, err
- }
-
- return &answer, nil
-}
-
-// GetService --
-func GetService(context context.Context, client k8sclient.Reader, name string, namespace string) (*corev1.Service, error) {
- key := k8sclient.ObjectKey{
- Name: name,
- Namespace: namespace,
- }
-
- answer := corev1.Service{
- TypeMeta: metav1.TypeMeta{
- Kind: "Service",
- APIVersion: "v1",
- },
- ObjectMeta: metav1.ObjectMeta{
- Name: name,
- Namespace: namespace,
- },
- }
-
- if err := client.Get(context, key, &answer); err != nil {
- return nil, err
- }
-
- return &answer, nil
-}
-
-// GetSecretRefValue returns the value of a secret in the supplied namespace --
-func GetSecretRefValue(ctx context.Context, client k8sclient.Reader, namespace string, selector *corev1.SecretKeySelector) (string, error) {
- secret, err := GetSecret(ctx, client, selector.Name, namespace)
- if err != nil {
- return "", err
- }
-
- if data, ok := secret.Data[selector.Key]; ok {
- return string(data), nil
- }
-
- return "", fmt.Errorf("key %s not found in secret %s", selector.Key, selector.Name)
-}
-
-// GetConfigMapRefValue returns the value of a configmap in the supplied namespace
-func GetConfigMapRefValue(ctx context.Context, client k8sclient.Reader, namespace string, selector *corev1.ConfigMapKeySelector) (string, error) {
- cm, err := GetConfigMap(ctx, client, selector.Name, namespace)
- if err != nil {
- return "", err
- }
-
- if data, ok := cm.Data[selector.Key]; ok {
- return data, nil
- }
-
- return "", fmt.Errorf("key %s not found in config map %s", selector.Key, selector.Name)
-}
-
-// ResolveValueSource --
-func ResolveValueSource(ctx context.Context, client k8sclient.Reader, namespace string, valueSource *v1.ValueSource) (string, error) {
- if valueSource.ConfigMapKeyRef != nil && valueSource.SecretKeyRef != nil {
- return "", fmt.Errorf("value source has bot config map and secret configured")
- }
- if valueSource.ConfigMapKeyRef != nil {
- return GetConfigMapRefValue(ctx, client, namespace, valueSource.ConfigMapKeyRef)
- }
- if valueSource.SecretKeyRef != nil {
- return GetSecretRefValue(ctx, client, namespace, valueSource.SecretKeyRef)
- }
-
- return "", nil
-}
diff --git a/pkg/util/kubernetes/wait.go b/pkg/util/kubernetes/wait.go
deleted file mode 100644
index 5c6129b..0000000
--- a/pkg/util/kubernetes/wait.go
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package kubernetes
-
-import (
- "context"
- "time"
-
- "github.com/apache/camel-k/pkg/client"
- "github.com/pkg/errors"
- "k8s.io/apimachinery/pkg/runtime"
-
- k8serrors "k8s.io/apimachinery/pkg/api/errors"
- k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
-)
-
-// ResourceRetrieveFunction --
-type ResourceRetrieveFunction func() (interface{}, error)
-
-// ResourceCheckFunction --
-type ResourceCheckFunction func(interface{}) (bool, error)
-
-const (
- sleepTime = 400 * time.Millisecond
-)
-
-// WaitCondition --
-func WaitCondition(ctx context.Context, c client.Client, obj runtime.Object, condition ResourceCheckFunction, maxDuration time.Duration) error {
- start := time.Now()
- key, err := k8sclient.ObjectKeyFromObject(obj)
- if err != nil {
- return err
- }
- for start.Add(maxDuration).After(time.Now()) {
- err := c.Get(ctx, key, obj)
- if err != nil {
- if k8serrors.IsNotFound(err) {
- time.Sleep(sleepTime)
- continue
- }
-
- return err
- }
-
- satisfied, err := condition(obj)
- if err != nil {
- return errors.Wrap(err, "error while evaluating condition")
- }
- if !satisfied {
- time.Sleep(sleepTime)
- continue
- }
-
- return nil
- }
- return errors.New("timeout while waiting condition")
-}
diff --git a/pkg/util/log/log.go b/pkg/util/log/log.go
deleted file mode 100644
index 8287561..0000000
--- a/pkg/util/log/log.go
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package log
-
-import (
- "fmt"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/go-logr/logr"
- logf "sigs.k8s.io/controller-runtime/pkg/log"
-)
-
-// Log --
-var Log Logger
-
-func init() {
- Log = Logger{
- delegate: logf.Log.WithName("camel-k"),
- }
-}
-
-// Injectable identifies objects that can receive a Logger
-type Injectable interface {
- InjectLogger(Logger)
-}
-
-// Logger --
-type Logger struct {
- delegate logr.Logger
-}
-
-// Debugf --
-func (l Logger) Debugf(format string, args ...interface{}) {
- l.delegate.V(1).Info(fmt.Sprintf(format, args...))
-}
-
-// Infof --
-func (l Logger) Infof(format string, args ...interface{}) {
- l.delegate.Info(fmt.Sprintf(format, args...))
-}
-
-// Errorf --
-func (l Logger) Errorf(err error, format string, args ...interface{}) {
- l.delegate.Error(err, fmt.Sprintf(format, args...))
-}
-
-// Debug --
-func (l Logger) Debug(msg string, keysAndValues ...interface{}) {
- l.delegate.V(1).Info(msg, keysAndValues...)
-}
-
-// Info --
-func (l Logger) Info(msg string, keysAndValues ...interface{}) {
- l.delegate.Info(msg, keysAndValues...)
-}
-
-// Error --
-func (l Logger) Error(err error, msg string, keysAndValues ...interface{}) {
- l.delegate.Error(err, msg, keysAndValues...)
-}
-
-// WithName --
-func (l Logger) WithName(name string) Logger {
- return Logger{
- delegate: l.delegate.WithName(name),
- }
-}
-
-// WithValues --
-func (l Logger) WithValues(keysAndValues ...interface{}) Logger {
- return Logger{
- delegate: l.delegate.WithValues(keysAndValues...),
- }
-}
-
-// ForBuild --
-func (l Logger) ForBuild(target *v1.Build) Logger {
- return l.WithValues(
- "api-version", target.APIVersion,
- "kind", target.Kind,
- "ns", target.Namespace,
- "name", target.Name,
- )
-}
-
-// ForIntegration --
-func (l Logger) ForIntegration(target *v1.Integration) Logger {
- return l.WithValues(
- "api-version", target.APIVersion,
- "kind", target.Kind,
- "ns", target.Namespace,
- "name", target.Name,
- )
-}
-
-// ForIntegrationKit --
-func (l Logger) ForIntegrationKit(target *v1.IntegrationKit) Logger {
- return l.WithValues(
- "api-version", target.APIVersion,
- "kind", target.Kind,
- "ns", target.Namespace,
- "name", target.Name,
- )
-}
-
-// ForIntegrationPlatform --
-func (l Logger) ForIntegrationPlatform(target *v1.IntegrationPlatform) Logger {
- return l.WithValues(
- "api-version", target.APIVersion,
- "kind", target.Kind,
- "ns", target.Namespace,
- "name", target.Name,
- )
-}
-
-// ***********************************
-//
-// Helpers
-//
-// ***********************************
-
-// WithName --
-func WithName(name string) Logger {
- return Log.WithName(name)
-}
-
-// WithValues --
-func WithValues(keysAndValues ...interface{}) Logger {
- return Log.WithValues(keysAndValues...)
-}
-
-// ForIntegration --
-func ForIntegration(target *v1.Integration) Logger {
- return Log.ForIntegration(target)
-}
-
-// ForIntegrationKit --
-func ForIntegrationKit(target *v1.IntegrationKit) Logger {
- return Log.ForIntegrationKit(target)
-}
-
-// ForIntegrationPlatform --
-func ForIntegrationPlatform(target *v1.IntegrationPlatform) Logger {
- return Log.ForIntegrationPlatform(target)
-}
-
-// ***********************************
-//
-//
-//
-// ***********************************
-
-// Debugf --
-func Debugf(format string, args ...interface{}) {
- Log.Debugf(format, args...)
-}
-
-// Infof --
-func Infof(format string, args ...interface{}) {
- Log.Infof(format, args...)
-}
-
-// Errorf --
-func Errorf(err error, format string, args ...interface{}) {
- Log.Errorf(err, format, args...)
-}
-
-// Debug --
-func Debug(msg string, keysAndValues ...interface{}) {
- Log.Debug(msg, keysAndValues...)
-}
-
-// Info --
-func Info(msg string, keysAndValues ...interface{}) {
- Log.Info(msg, keysAndValues...)
-}
-
-// Error --
-func Error(err error, msg string, keysAndValues ...interface{}) {
- Log.Error(err, msg, keysAndValues...)
-}
diff --git a/pkg/util/maven/maven.go b/pkg/util/maven/maven.go
deleted file mode 100644
index 067feca..0000000
--- a/pkg/util/maven/maven.go
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package maven
-
-import (
- "context"
- "fmt"
- "io"
- "io/ioutil"
- "math"
- "os"
- "os/exec"
- "path"
- "regexp"
- "strings"
-
- "github.com/pkg/errors"
-
- "github.com/apache/camel-k/pkg/util"
- "github.com/apache/camel-k/pkg/util/log"
-)
-
-// Log --
-var Log = log.WithName("maven")
-
-// GenerateProjectStructure --
-func GenerateProjectStructure(context Context) error {
- if err := util.WriteFileWithBytesMarshallerContent(context.Path, "pom.xml", context.Project); err != nil {
- return err
- }
-
- if context.SettingsContent != nil {
- if err := util.WriteFileWithContent(context.Path, "settings.xml", context.SettingsContent); err != nil {
- return err
- }
- }
-
- for k, v := range context.AdditionalEntries {
- var bytes []byte
- var err error
-
- if dc, ok := v.([]byte); ok {
- bytes = dc
- } else if dc, ok := v.(io.Reader); ok {
- bytes, err = ioutil.ReadAll(dc)
- if err != nil {
- return err
- }
- } else {
- return fmt.Errorf("unknown content type: name=%s, content=%+v", k, v)
- }
-
- if len(bytes) > 0 {
- Log.Infof("write entry: %s (%d bytes)", k, len(bytes))
-
- err = util.WriteFileWithContent(context.Path, k, bytes)
- if err != nil {
- return err
- }
- }
- }
-
- return nil
-}
-
-// Run --
-func Run(ctx Context) error {
- if err := GenerateProjectStructure(ctx); err != nil {
- return err
- }
-
- mvnCmd := "mvn"
- if c, ok := os.LookupEnv("MAVEN_CMD"); ok {
- mvnCmd = c
- }
-
- args := make([]string, 0)
- args = append(args, "--batch-mode")
-
- if ctx.LocalRepository == "" {
- args = append(args, "-Dcamel.noop=true")
- } else if _, err := os.Stat(ctx.LocalRepository); err == nil {
- args = append(args, "-Dmaven.repo.local="+ctx.LocalRepository)
- }
-
- settingsPath := path.Join(ctx.Path, "settings.xml")
- settingsExists, err := util.FileExists(settingsPath)
- if err != nil {
- return err
- }
-
- if settingsExists {
- args = append(args, "--settings", settingsPath)
- }
-
- args = append(args, ctx.AdditionalArguments...)
-
- timeout := ctx.Timeout
- if timeout == 0 {
- timeout = math.MaxInt64
- }
-
- c, cancel := context.WithTimeout(context.Background(), timeout)
- defer cancel()
-
- cmd := exec.CommandContext(c, mvnCmd, args...)
- cmd.Dir = ctx.Path
- cmd.Stderr = os.Stderr
- if ctx.Stdout != nil {
- cmd.Stdout = ctx.Stdout
- } else {
- cmd.Stdout = os.Stdout
- }
-
- Log.WithValues("timeout", timeout.String()).Infof("executing: %s", strings.Join(cmd.Args, " "))
-
- return cmd.Run()
-}
-
-// ParseGAV decode a maven artifact id to a dependency definition.
-//
-// The artifact id is in the form of:
-//
-// <groupId>:<artifactId>[:<packagingType>[:<classifier>]]:(<version>|'?')
-//
-func ParseGAV(gav string) (Dependency, error) {
- // <groupId>:<artifactId>[:<packagingType>[:<classifier>]]:(<version>|'?')
- dep := Dependency{}
- rex := regexp.MustCompile("([^: ]+):([^: ]+)(:([^: ]*)(:([^: ]+))?)?(:([^: ]+))?")
- res := rex.FindStringSubmatch(gav)
-
- if res == nil || len(res) < 9 {
- return Dependency{}, errors.New("GAV must match <groupId>:<artifactId>[:<packagingType>[:<classifier>]]:(<version>|'?')")
- }
-
- dep.GroupID = res[1]
- dep.ArtifactID = res[2]
-
- cnt := strings.Count(gav, ":")
- switch cnt {
- case 2:
- dep.Version = res[4]
- case 3:
- dep.Type = res[4]
- dep.Version = res[6]
- default:
- dep.Type = res[4]
- dep.Classifier = res[6]
- dep.Version = res[8]
- }
-
- return dep, nil
-}
diff --git a/pkg/util/maven/maven_project.go b/pkg/util/maven/maven_project.go
deleted file mode 100644
index 4de5225..0000000
--- a/pkg/util/maven/maven_project.go
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package maven
-
-import (
- "bytes"
- "encoding/xml"
- "strings"
-)
-
-// NewProject --
-func NewProject() Project {
- return Project{
- XMLName: xml.Name{Local: "project"},
- XMLNs: "http://maven.apache.org/POM/4.0.0",
- XMLNsXsi: "http://www.w3.org/2001/XMLSchema-instance",
- XsiSchemaLocation: "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd",
- ModelVersion: "4.0.0",
- }
-}
-
-// NewProjectWithGAV --
-func NewProjectWithGAV(group string, artifact string, version string) Project {
- p := NewProject()
- p.GroupID = group
- p.ArtifactID = artifact
- p.Version = version
- p.Properties = make(map[string]string)
- p.Properties["project.build.sourceEncoding"] = "UTF-8"
-
- return p
-}
-
-// MarshalBytes --
-func (p Project) MarshalBytes() ([]byte, error) {
- w := &bytes.Buffer{}
- w.WriteString(xml.Header)
-
- e := xml.NewEncoder(w)
- e.Indent("", " ")
-
- err := e.Encode(p)
- if err != nil {
- return []byte{}, err
- }
-
- return w.Bytes(), nil
-}
-
-// LookupDependency --
-func (p *Project) LookupDependency(dep Dependency) *Dependency {
- for i := range p.Dependencies {
- // Check if the given dependency is already included in the dependency list
- if p.Dependencies[i].GroupID == dep.GroupID && p.Dependencies[i].ArtifactID == dep.ArtifactID {
- return &p.Dependencies[i]
- }
- }
-
- return nil
-}
-
-// ReplaceDependency --
-func (p *Project) ReplaceDependency(dep Dependency) {
- for i, d := range p.Dependencies {
- // Check if the given dependency is already included in the dependency list
- if d.GroupID == dep.GroupID && d.ArtifactID == dep.ArtifactID {
- p.Dependencies[i] = dep
-
- return
- }
- }
-}
-
-// AddDependency adds a dependency to maven's dependencies
-func (p *Project) AddDependency(dep Dependency) {
- for _, d := range p.Dependencies {
- // Check if the given dependency is already included in the dependency list
- if d.GroupID == dep.GroupID && d.ArtifactID == dep.ArtifactID {
- return
- }
- }
-
- p.Dependencies = append(p.Dependencies, dep)
-}
-
-// AddDependencies adds dependencies to maven's dependencies
-func (p *Project) AddDependencies(deps ...Dependency) {
- for _, d := range deps {
- p.AddDependency(d)
- }
-}
-
-// AddDependencyGAV a dependency to maven's dependencies
-func (p *Project) AddDependencyGAV(groupID string, artifactID string, version string) {
- p.AddDependency(NewDependency(groupID, artifactID, version))
-}
-
-// AddEncodedDependencyGAV a dependency to maven's dependencies
-func (p *Project) AddEncodedDependencyGAV(gav string) {
- if d, err := ParseGAV(gav); err == nil {
- // TODO: error handling
- p.AddDependency(d)
- }
-}
-
-// AddDependencyExclusion --
-func (p *Project) AddDependencyExclusion(dep Dependency, exclusion Exclusion) {
- if t := p.LookupDependency(dep); t != nil {
- if t.Exclusions == nil {
- exclusions := make([]Exclusion, 0)
- t.Exclusions = &exclusions
- }
-
- for _, e := range *t.Exclusions {
- if e.ArtifactID == exclusion.ArtifactID && e.GroupID == exclusion.GroupID {
- return
- }
- }
-
- *t.Exclusions = append(*t.Exclusions, exclusion)
- }
-}
-
-// AddDependencyExclusions --
-func (p *Project) AddDependencyExclusions(dep Dependency, exclusions ...Exclusion) {
- for _, e := range exclusions {
- p.AddDependencyExclusion(dep, e)
- }
-}
-
-// NewDependency create an new dependency from the given gav info
-func NewDependency(groupID string, artifactID string, version string) Dependency {
- return Dependency{
- GroupID: groupID,
- ArtifactID: artifactID,
- Version: version,
- Type: "",
- Classifier: "",
- }
-}
-
-//
-// NewRepository parse the given repo url ang generated the related struct.
-//
-// The repository can be customized by appending @instruction to the repository
-// uri, as example:
-//
-// http://my-nexus:8081/repository/publicc@id=my-repo@snapshots
-//
-// Will enable snapshots and sets the repo it to my-repo
-//
-func NewRepository(repo string) Repository {
- r := Repository{
- URL: repo,
- Releases: RepositoryPolicy{
- Enabled: true,
- ChecksumPolicy: "fail",
- },
- Snapshots: RepositoryPolicy{
- Enabled: false,
- ChecksumPolicy: "fail",
- },
- }
-
- if idx := strings.Index(repo, "@"); idx != -1 {
- r.URL = repo[:idx]
-
- for _, attribute := range strings.Split(repo[idx+1:], "@") {
- switch {
- case attribute == "snapshots":
- r.Snapshots.Enabled = true
- case attribute == "noreleases":
- r.Releases.Enabled = false
- case strings.HasPrefix(attribute, "id="):
- r.ID = attribute[3:]
- case strings.HasPrefix(attribute, "checksumpolicy="):
- r.Snapshots.ChecksumPolicy = attribute[15:]
- r.Releases.ChecksumPolicy = attribute[15:]
- }
- }
- }
-
- return r
-}
diff --git a/pkg/util/maven/maven_project_test.go b/pkg/util/maven/maven_project_test.go
deleted file mode 100644
index 164734c..0000000
--- a/pkg/util/maven/maven_project_test.go
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package maven
-
-import (
- "testing"
-
- "github.com/apache/camel-k/pkg/util"
-
- "github.com/stretchr/testify/assert"
-)
-
-const expectedPom = `<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ` +
- `xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.apache.camel.k.integration</groupId>
- <artifactId>camel-k-integration</artifactId>
- <version>1.0.0</version>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </properties>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.apache.camel</groupId>
- <artifactId>camel-bom</artifactId>
- <version>2.22.1</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.apache.camel.k</groupId>
- <artifactId>camel-k-runtime-jvm</artifactId>
- <version>1.0.0</version>
- </dependency>
- </dependencies>
- <repositories>
- <repository>
- <id>central</id>
- <url>https://repo.maven.apache.org/maven2</url>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- <releases>
- <enabled>true</enabled>
- <updatePolicy>never</updatePolicy>
- </releases>
- </repository>
- </repositories>
- <pluginRepositories>
- <pluginRepository>
- <id>central</id>
- <url>https://repo.maven.apache.org/maven2</url>
- <snapshots>
- <enabled>false</enabled>
- </snapshots>
- <releases>
- <enabled>true</enabled>
- <updatePolicy>never</updatePolicy>
- </releases>
- </pluginRepository>
- </pluginRepositories>
-</project>`
-
-func TestPomGeneration(t *testing.T) {
- project := NewProjectWithGAV("org.apache.camel.k.integration", "camel-k-integration", "1.0.0")
- project.DependencyManagement = &DependencyManagement{
- Dependencies: []Dependency{
- {
- GroupID: "org.apache.camel",
- ArtifactID: "camel-bom",
- Version: "2.22.1",
- Type: "pom",
- Scope: "import",
- },
- },
- }
- project.Dependencies = []Dependency{
- {
- GroupID: "org.apache.camel.k",
- ArtifactID: "camel-k-runtime-jvm",
- Version: "1.0.0",
- },
- }
- project.Repositories = []Repository{
- {
- ID: "central",
- URL: "https://repo.maven.apache.org/maven2",
- Snapshots: RepositoryPolicy{
- Enabled: false,
- },
- Releases: RepositoryPolicy{
- Enabled: true,
- UpdatePolicy: "never",
- },
- },
- }
- project.PluginRepositories = []Repository{
- {
- ID: "central",
- URL: "https://repo.maven.apache.org/maven2",
- Snapshots: RepositoryPolicy{
- Enabled: false,
- },
- Releases: RepositoryPolicy{
- Enabled: true,
- UpdatePolicy: "never",
- },
- },
- }
-
- pom, err := util.EncodeXML(project)
-
- assert.Nil(t, err)
- assert.NotNil(t, pom)
-
- assert.Equal(t, expectedPom, string(pom))
-}
-
-func TestParseSimpleGAV(t *testing.T) {
- dep, err := ParseGAV("org.apache.camel:camel-core:2.21.1")
-
- assert.Nil(t, err)
- assert.Equal(t, dep.GroupID, "org.apache.camel")
- assert.Equal(t, dep.ArtifactID, "camel-core")
- assert.Equal(t, dep.Version, "2.21.1")
- assert.Equal(t, dep.Type, "")
- assert.Equal(t, dep.Classifier, "")
-}
-
-func TestParseGAVWithType(t *testing.T) {
- dep, err := ParseGAV("org.apache.camel:camel-core:war:2.21.1")
-
- assert.Nil(t, err)
- assert.Equal(t, dep.GroupID, "org.apache.camel")
- assert.Equal(t, dep.ArtifactID, "camel-core")
- assert.Equal(t, dep.Version, "2.21.1")
- assert.Equal(t, dep.Type, "war")
- assert.Equal(t, dep.Classifier, "")
-}
-
-func TestParseGAVWithClassifierAndType(t *testing.T) {
- dep, err := ParseGAV("org.apache.camel:camel-core:war:test:2.21.1")
-
- assert.Nil(t, err)
- assert.Equal(t, dep.GroupID, "org.apache.camel")
- assert.Equal(t, dep.ArtifactID, "camel-core")
- assert.Equal(t, dep.Version, "2.21.1")
- assert.Equal(t, dep.Type, "war")
- assert.Equal(t, dep.Classifier, "test")
-}
-
-func TestParseGAVMvnNoVersion(t *testing.T) {
- dep, err := ParseGAV("mvn:org.apache.camel/camel-core")
-
- assert.Nil(t, err)
- assert.Equal(t, dep.GroupID, "mvn")
- assert.Equal(t, dep.ArtifactID, "org.apache.camel/camel-core")
-}
-
-func TestParseGAVErrorNoColumn(t *testing.T) {
- dep, err := ParseGAV("org.apache.camel.k.camel-k-runtime-noop-0.2.1-SNAPSHOT.jar")
-
- assert.EqualError(t, err, "GAV must match <groupId>:<artifactId>[:<packagingType>[:<classifier>]]:(<version>|'?')")
- assert.Equal(t, Dependency{}, dep)
-}
-
-func TestNewRepository(t *testing.T) {
- r := NewRepository("http://nexus/public")
- assert.Equal(t, "", r.ID)
- assert.Equal(t, "http://nexus/public", r.URL)
- assert.True(t, r.Releases.Enabled)
- assert.False(t, r.Snapshots.Enabled)
- assert.Equal(t, "fail", r.Releases.ChecksumPolicy)
- assert.Equal(t, "fail", r.Snapshots.ChecksumPolicy)
-}
-
-func TestNewRepositoryWithSnapshots(t *testing.T) {
- r := NewRepository("http://nexus/public@snapshots")
- assert.Equal(t, "", r.ID)
- assert.Equal(t, "http://nexus/public", r.URL)
- assert.True(t, r.Releases.Enabled)
- assert.True(t, r.Snapshots.Enabled)
- assert.Equal(t, "fail", r.Releases.ChecksumPolicy)
- assert.Equal(t, "fail", r.Snapshots.ChecksumPolicy)
-}
-
-func TestNewRepositoryWithSnapshotsAndID(t *testing.T) {
- r := NewRepository("http://nexus/public@snapshots@id=test")
- assert.Equal(t, "test", r.ID)
- assert.Equal(t, "http://nexus/public", r.URL)
- assert.True(t, r.Releases.Enabled)
- assert.True(t, r.Snapshots.Enabled)
- assert.Equal(t, "fail", r.Releases.ChecksumPolicy)
- assert.Equal(t, "fail", r.Snapshots.ChecksumPolicy)
-}
-
-func TestNewRepositoryWithID(t *testing.T) {
- r := NewRepository("http://nexus/public@id=test")
- assert.Equal(t, "test", r.ID)
- assert.Equal(t, "http://nexus/public", r.URL)
- assert.True(t, r.Releases.Enabled)
- assert.False(t, r.Snapshots.Enabled)
- assert.Equal(t, "fail", r.Releases.ChecksumPolicy)
- assert.Equal(t, "fail", r.Snapshots.ChecksumPolicy)
-}
-
-func TestNewRepositoryWithChecksumPolicy(t *testing.T) {
- r := NewRepository("http://nexus/public@checksumpolicy=warn")
- assert.Equal(t, "", r.ID)
- assert.Equal(t, "http://nexus/public", r.URL)
- assert.True(t, r.Releases.Enabled)
- assert.False(t, r.Snapshots.Enabled)
- assert.Equal(t, "warn", r.Releases.ChecksumPolicy)
- assert.Equal(t, "warn", r.Snapshots.ChecksumPolicy)
-}
diff --git a/pkg/util/maven/maven_settings.go b/pkg/util/maven/maven_settings.go
deleted file mode 100644
index 4bdf282..0000000
--- a/pkg/util/maven/maven_settings.go
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package maven
-
-import (
- "encoding/xml"
- "strings"
-
- "github.com/apache/camel-k/pkg/util"
-
- corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-)
-
-// DefaultMavenRepositories is a comma separated list of default maven repositories
-// This variable can be overridden at build time
-var DefaultMavenRepositories = "https://repo.maven.apache.org/maven2@id=central"
-
-// NewSettings --
-func NewSettings() Settings {
- return Settings{
- XMLName: xml.Name{Local: "settings"},
- XMLNs: "http://maven.apache.org/SETTINGS/1.0.0",
- XMLNsXsi: "http://www.w3.org/2001/XMLSchema-instance",
- XsiSchemaLocation: "http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd",
- }
-}
-
-// NewDefaultSettings --
-func NewDefaultSettings(repositories []Repository) Settings {
- settings := NewSettings()
-
- var additionalRepos []Repository
- for _, defaultRepo := range getDefaultMavenRepositories() {
- if !containsRepo(repositories, defaultRepo.ID) {
- additionalRepos = append(additionalRepos, defaultRepo)
- }
- }
- if len(additionalRepos) > 0 {
- repositories = append(additionalRepos, repositories...)
- }
-
- settings.Profiles = []Profile{
- {
- ID: "maven-settings",
- Activation: Activation{
- ActiveByDefault: true,
- },
- Repositories: repositories,
- PluginRepositories: repositories,
- },
- }
-
- return settings
-}
-
-// CreateSettingsConfigMap --
-func CreateSettingsConfigMap(namespace string, name string, settings Settings) (*corev1.ConfigMap, error) {
- data, err := util.EncodeXML(settings)
- if err != nil {
- return nil, err
- }
-
- cm := &corev1.ConfigMap{
- TypeMeta: metav1.TypeMeta{
- Kind: "ConfigMap",
- APIVersion: "v1",
- },
- ObjectMeta: metav1.ObjectMeta{
- Name: name + "-maven-settings",
- Namespace: namespace,
- Labels: map[string]string{
- "app": "camel-k",
- },
- },
- Data: map[string]string{
- "settings.xml": string(data),
- },
- }
-
- return cm, nil
-}
-
-func getDefaultMavenRepositories() (repos []Repository) {
- for _, repoDesc := range strings.Split(DefaultMavenRepositories, ",") {
- repos = append(repos, NewRepository(repoDesc))
- }
- return
-}
-
-func containsRepo(repositories []Repository, id string) bool {
- for _, r := range repositories {
- if r.ID == id {
- return true
- }
- }
- return false
-}
diff --git a/pkg/util/maven/maven_settings_test.go b/pkg/util/maven/maven_settings_test.go
deleted file mode 100644
index a4a1776..0000000
--- a/pkg/util/maven/maven_settings_test.go
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package maven
-
-import (
- "testing"
-
- "github.com/apache/camel-k/pkg/util"
- "github.com/stretchr/testify/assert"
-)
-
-const expectedSettings = `<?xml version="1.0" encoding="UTF-8"?>
-<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ` +
- `xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
- <localRepository>/tmp/artifacts/m2</localRepository>
- <profiles>
- <profile>
- <id>my-profile</id>
- <activation>
- <activeByDefault>true</activeByDefault>
- </activation>
- <repositories>
- <repository>
- <id>central</id>
- <url>https://repo.maven.apache.org/maven2</url>
- <snapshots>
- <enabled>false</enabled>
- <checksumPolicy>warn</checksumPolicy>
- </snapshots>
- <releases>
- <enabled>true</enabled>
- <updatePolicy>never</updatePolicy>
- <checksumPolicy>fail</checksumPolicy>
- </releases>
- </repository>
- </repositories>
- <pluginRepositories></pluginRepositories>
- </profile>
- </profiles>
-</settings>`
-
-const expectedDefaultSettings = `<?xml version="1.0" encoding="UTF-8"?>
-<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ` +
- `xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
- <localRepository></localRepository>
- <profiles>
- <profile>
- <id>maven-settings</id>
- <activation>
- <activeByDefault>true</activeByDefault>
- </activation>
- <repositories>
- <repository>
- <id>central</id>
- <url>https://repo.maven.apache.org/maven2</url>
- <snapshots>
- <enabled>false</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </snapshots>
- <releases>
- <enabled>true</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </releases>
- </repository>
- </repositories>
- <pluginRepositories>
- <pluginRepository>
- <id>central</id>
- <url>https://repo.maven.apache.org/maven2</url>
- <snapshots>
- <enabled>false</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </snapshots>
- <releases>
- <enabled>true</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </releases>
- </pluginRepository>
- </pluginRepositories>
- </profile>
- </profiles>
-</settings>`
-
-const expectedDefaultSettingsWithExtraRepo = `<?xml version="1.0" encoding="UTF-8"?>
-<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ` +
- `xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
- <localRepository></localRepository>
- <profiles>
- <profile>
- <id>maven-settings</id>
- <activation>
- <activeByDefault>true</activeByDefault>
- </activation>
- <repositories>
- <repository>
- <id>central</id>
- <url>https://repo1.maven.org/maven2</url>
- <snapshots>
- <enabled>false</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </snapshots>
- <releases>
- <enabled>true</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </releases>
- </repository>
- <repository>
- <id>foo</id>
- <url>https://foo.bar.org/repo</url>
- <snapshots>
- <enabled>false</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </snapshots>
- <releases>
- <enabled>true</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </releases>
- </repository>
- </repositories>
- <pluginRepositories>
- <pluginRepository>
- <id>central</id>
- <url>https://repo1.maven.org/maven2</url>
- <snapshots>
- <enabled>false</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </snapshots>
- <releases>
- <enabled>true</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </releases>
- </pluginRepository>
- <pluginRepository>
- <id>foo</id>
- <url>https://foo.bar.org/repo</url>
- <snapshots>
- <enabled>false</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </snapshots>
- <releases>
- <enabled>true</enabled>
- <checksumPolicy>fail</checksumPolicy>
- </releases>
- </pluginRepository>
- </pluginRepositories>
- </profile>
- </profiles>
-</settings>`
-
-func TestSettingsGeneration(t *testing.T) {
- settings := NewSettings()
- settings.LocalRepository = "/tmp/artifacts/m2"
- settings.Profiles = []Profile{
- {
- ID: "my-profile",
- Activation: Activation{
- ActiveByDefault: true,
- },
- Repositories: []Repository{
- {
- ID: "central",
- URL: "https://repo.maven.apache.org/maven2",
- Snapshots: RepositoryPolicy{
- Enabled: false,
- ChecksumPolicy: "warn",
- },
- Releases: RepositoryPolicy{
- Enabled: true,
- UpdatePolicy: "never",
- ChecksumPolicy: "fail",
- },
- },
- },
- },
- }
-
- content, err := util.EncodeXML(settings)
-
- assert.Nil(t, err)
- assert.NotNil(t, settings)
-
- assert.Equal(t, expectedSettings, string(content))
-}
-
-func TestDefaultSettingsGeneration(t *testing.T) {
- settings := NewDefaultSettings([]Repository{})
-
- content, err := util.EncodeXML(settings)
-
- assert.Nil(t, err)
- assert.NotNil(t, settings)
-
- assert.Equal(t, expectedDefaultSettings, string(content))
-}
-
-func TestDefaultSettingsGenerationWithAdditionalRepo(t *testing.T) {
- repositories := []Repository{
- NewRepository("https://repo1.maven.org/maven2@id=central"),
- NewRepository("https://foo.bar.org/repo@id=foo"),
- }
- settings := NewDefaultSettings(repositories)
-
- content, err := util.EncodeXML(settings)
-
- assert.Nil(t, err)
- assert.NotNil(t, settings)
-
- assert.Equal(t, expectedDefaultSettingsWithExtraRepo, string(content))
-}
-
-func TestCreateSettingsConfigMap(t *testing.T) {
- settings := NewDefaultSettings([]Repository{})
-
- configMap, err := CreateSettingsConfigMap("foo", "bar", settings)
- assert.Nil(t, err)
- assert.NotNil(t, configMap)
-
- content, err := util.EncodeXML(settings)
-
- assert.Nil(t, err)
- assert.NotNil(t, settings)
-
- assert.Equal(t, string(content), configMap.Data["settings.xml"])
-}
diff --git a/pkg/util/maven/maven_types.go b/pkg/util/maven/maven_types.go
deleted file mode 100644
index 44cbf71..0000000
--- a/pkg/util/maven/maven_types.go
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package maven
-
-import (
- "bytes"
- "encoding/xml"
- "fmt"
- "io"
- "time"
-)
-
-// Repository --
-type Repository struct {
- ID string `xml:"id"`
- Name string `xml:"name,omitempty"`
- URL string `xml:"url"`
- Snapshots RepositoryPolicy `xml:"snapshots,omitempty"`
- Releases RepositoryPolicy `xml:"releases,omitempty"`
-}
-
-// RepositoryPolicy --
-type RepositoryPolicy struct {
- Enabled bool `xml:"enabled"`
- UpdatePolicy string `xml:"updatePolicy,omitempty"`
- ChecksumPolicy string `xml:"checksumPolicy,omitempty"`
-}
-
-// Build --
-type Build struct {
- DefaultGoal string `xml:"defaultGoal,omitempty"`
- Plugins []Plugin `xml:"plugins>plugin,omitempty"`
-}
-
-// Plugin --
-type Plugin struct {
- GroupID string `xml:"groupId"`
- ArtifactID string `xml:"artifactId"`
- Version string `xml:"version,omitempty"`
- Executions []Execution `xml:"executions>execution,omitempty"`
- Dependencies []Dependency `xml:"dependencies>dependency,omitempty"`
-}
-
-// Execution --
-type Execution struct {
- ID string `xml:"id,omitempty"`
- Phase string `xml:"phase,omitempty"`
- Goals []string `xml:"goals>goal,omitempty"`
-}
-
-// Properties --
-type Properties map[string]string
-
-type propertiesEntry struct {
- XMLName xml.Name
- Value string `xml:",chardata"`
-}
-
-// AddAll --
-func (m Properties) AddAll(properties map[string]string) {
- for k, v := range properties {
- m[k] = v
- }
-}
-
-// MarshalXML --
-func (m Properties) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
- if len(m) == 0 {
- return nil
- }
-
- err := e.EncodeToken(start)
- if err != nil {
- return err
- }
-
- for k, v := range m {
- if err := e.Encode(propertiesEntry{XMLName: xml.Name{Local: k}, Value: v}); err != nil {
- return err
- }
- }
-
- return e.EncodeToken(start.End())
-}
-
-// NewContext --
-func NewContext(buildDir string, project Project) Context {
- return Context{
- Path: buildDir,
- Project: project,
- AdditionalArguments: make([]string, 0),
- AdditionalEntries: make(map[string]interface{}),
- }
-}
-
-// Context --
-type Context struct {
- Path string
- Project Project
- SettingsContent []byte
- AdditionalArguments []string
- AdditionalEntries map[string]interface{}
- Timeout time.Duration
- LocalRepository string
- Stdout io.Writer
-}
-
-// AddEntry --
-func (c *Context) AddEntry(id string, entry interface{}) {
- if c.AdditionalEntries == nil {
- c.AdditionalEntries = make(map[string]interface{})
- }
-
- c.AdditionalEntries[id] = entry
-}
-
-// AddArgument --
-func (c *Context) AddArgument(argument string) {
- c.AdditionalArguments = append(c.AdditionalArguments, argument)
-}
-
-// AddArgumentf --
-func (c *Context) AddArgumentf(format string, args ...interface{}) {
- c.AdditionalArguments = append(c.AdditionalArguments, fmt.Sprintf(format, args...))
-}
-
-// AddArguments --
-func (c *Context) AddArguments(arguments ...string) {
- c.AdditionalArguments = append(c.AdditionalArguments, arguments...)
-}
-
-// AddSystemProperty --
-func (c *Context) AddSystemProperty(name string, value string) {
- c.AddArgumentf("-D%s=%s", name, value)
-}
-
-// Settings represent a maven settings
-type Settings struct {
- XMLName xml.Name
- XMLNs string `xml:"xmlns,attr"`
- XMLNsXsi string `xml:"xmlns:xsi,attr"`
- XsiSchemaLocation string `xml:"xsi:schemaLocation,attr"`
- LocalRepository string `xml:"localRepository"`
- Profiles []Profile `xml:"profiles>profile,omitempty"`
-}
-
-// MarshalBytes --
-func (s Settings) MarshalBytes() ([]byte, error) {
- w := &bytes.Buffer{}
- w.WriteString(xml.Header)
-
- e := xml.NewEncoder(w)
- e.Indent("", " ")
-
- err := e.Encode(s)
- if err != nil {
- return []byte{}, err
- }
-
- return w.Bytes(), nil
-}
-
-// Project represent a maven project
-type Project struct {
- XMLName xml.Name
- XMLNs string `xml:"xmlns,attr"`
- XMLNsXsi string `xml:"xmlns:xsi,attr"`
- XsiSchemaLocation string `xml:"xsi:schemaLocation,attr"`
- ModelVersion string `xml:"modelVersion"`
- GroupID string `xml:"groupId"`
- ArtifactID string `xml:"artifactId"`
- Version string `xml:"version"`
- Properties Properties `xml:"properties,omitempty"`
- DependencyManagement *DependencyManagement `xml:"dependencyManagement"`
- Dependencies []Dependency `xml:"dependencies>dependency,omitempty"`
- Repositories []Repository `xml:"repositories>repository,omitempty"`
- PluginRepositories []Repository `xml:"pluginRepositories>pluginRepository,omitempty"`
- Build *Build `xml:"build,omitempty"`
-}
-
-// Exclusion represent a maven's dependency exlucsion
-type Exclusion struct {
- GroupID string `xml:"groupId" yaml:"groupId"`
- ArtifactID string `xml:"artifactId" yaml:"artifactId"`
-}
-
-// DependencyManagement represent maven's dependency management block
-type DependencyManagement struct {
- Dependencies []Dependency `xml:"dependencies>dependency,omitempty"`
-}
-
-// Dependency represent a maven's dependency
-type Dependency struct {
- GroupID string `xml:"groupId" yaml:"groupId"`
- ArtifactID string `xml:"artifactId" yaml:"artifactId"`
- Version string `xml:"version,omitempty" yaml:"version,omitempty"`
- Type string `xml:"type,omitempty" yaml:"type,omitempty"`
- Classifier string `xml:"classifier,omitempty" yaml:"classifier,omitempty"`
- Scope string `xml:"scope,omitempty" yaml:"scope,omitempty"`
- Exclusions *[]Exclusion `xml:"exclusions>exclusion,omitempty" yaml:"exclusions,omitempty"`
-}
-
-// Profile --
-type Profile struct {
- ID string `xml:"id"`
- Activation Activation `xml:"activation,omitempty"`
- Properties Properties `xml:"properties,omitempty"`
- Repositories []Repository `xml:"repositories>repository,omitempty"`
- PluginRepositories []Repository `xml:"pluginRepositories>pluginRepository,omitempty"`
-}
-
-// Activation --
-type Activation struct {
- ActiveByDefault bool `xml:"activeByDefault"`
- Property *PropertyActivation `xml:"property,omitempty"`
-}
-
-// PropertyActivation --
-type PropertyActivation struct {
- Name string `xml:"name"`
- Value string `xml:"value"`
-}
diff --git a/pkg/util/minikube/registry.go b/pkg/util/minikube/registry.go
deleted file mode 100644
index 6ad5faa..0000000
--- a/pkg/util/minikube/registry.go
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-// Package minishift contains utilities for Minishift deployments
-package minikube
-
-import (
- "context"
- "strconv"
-
- corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
-
- "github.com/apache/camel-k/pkg/client"
-)
-
-const (
- registryNamespace = "kube-system"
-)
-
-// FindRegistry returns the Minikube addon registry location if any
-func FindRegistry(ctx context.Context, c client.Client) (*string, error) {
- svcs := corev1.ServiceList{
- TypeMeta: metav1.TypeMeta{
- APIVersion: corev1.SchemeGroupVersion.String(),
- Kind: "Service",
- },
- }
- err := c.List(ctx, &svcs,
- k8sclient.InNamespace(registryNamespace),
- k8sclient.MatchingLabels{
- "kubernetes.io/minikube-addons": "registry",
- })
- if err != nil {
- return nil, err
- }
- if len(svcs.Items) == 0 {
- return nil, nil
- }
- svc := svcs.Items[0]
- ip := svc.Spec.ClusterIP
- portStr := ""
- if len(svc.Spec.Ports) > 0 {
- port := svc.Spec.Ports[0].Port
- if port > 0 && port != 80 {
- portStr = ":" + strconv.FormatInt(int64(port), 10)
- }
- }
- registry := ip + portStr
- return ®istry, nil
-}
diff --git a/pkg/util/monitoring/register.go b/pkg/util/monitoring/register.go
deleted file mode 100644
index f18ba06..0000000
--- a/pkg/util/monitoring/register.go
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package monitoring
-
-import (
- monitoringv1 "github.com/coreos/prometheus-operator/pkg/apis/monitoring/v1"
- "github.com/sirupsen/logrus"
- "k8s.io/apimachinery/pkg/runtime"
-)
-
-type registerFunction func(*runtime.Scheme) error
-
-// AddToScheme adds monitoring types to the scheme
-func AddToScheme(scheme *runtime.Scheme) error {
- var err error
-
- err = doAdd(monitoringv1.AddToScheme, scheme, err)
-
- return err
-}
-
-func doAdd(addToScheme registerFunction, scheme *runtime.Scheme, err error) error {
- callErr := addToScheme(scheme)
- if callErr != nil {
- logrus.Error("Error while registering monitoring types", callErr)
- }
-
- if err == nil {
- return callErr
- }
- return err
-}
diff --git a/pkg/util/olm/available.go b/pkg/util/olm/available.go
deleted file mode 100644
index eb4b7da..0000000
--- a/pkg/util/olm/available.go
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package olm
-
-import (
- "context"
-
- kubernetesutils "github.com/apache/camel-k/pkg/util/kubernetes"
- olmv1 "github.com/operator-framework/operator-lifecycle-manager/pkg/api/apis/operators/v1"
- olmv1alpha1 "github.com/operator-framework/operator-lifecycle-manager/pkg/api/apis/operators/v1alpha1"
- k8serrors "k8s.io/apimachinery/pkg/api/errors"
- "k8s.io/apimachinery/pkg/runtime/schema"
- "k8s.io/client-go/kubernetes"
-)
-
-// IsAPIAvailable returns true if we are connected to a cluster with OLM installed
-//
-// This method should not be called from the operator, as it might require permissions that are not available.
-func IsAPIAvailable(ctx context.Context, c kubernetes.Interface, namespace string) (bool, error) {
- // check some Knative APIs
- for _, api := range getOLMGroupVersions() {
- if installed, err := isAvailable(c, api); err != nil {
- return false, err
- } else if installed {
- return true, nil
- }
- }
-
- return false, nil
-}
-
-func isAvailable(c kubernetes.Interface, api schema.GroupVersion) (bool, error) {
- _, err := c.Discovery().ServerResourcesForGroupVersion(api.String())
- if err != nil && (k8serrors.IsNotFound(err) || kubernetesutils.IsUnknownAPIError(err)) {
- return false, nil
- } else if err != nil {
- return false, err
- }
- return true, nil
-}
-
-func getOLMGroupVersions() []schema.GroupVersion {
- return []schema.GroupVersion{
- olmv1alpha1.SchemeGroupVersion,
- olmv1.SchemeGroupVersion,
- }
-}
diff --git a/pkg/util/olm/operator.go b/pkg/util/olm/operator.go
deleted file mode 100644
index e6ce7e7..0000000
--- a/pkg/util/olm/operator.go
+++ /dev/null
@@ -1,292 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package olm
-
-import (
- "context"
- "fmt"
- "strings"
-
- "github.com/apache/camel-k/pkg/client"
- "github.com/apache/camel-k/pkg/util/kubernetes"
- olmv1 "github.com/operator-framework/operator-lifecycle-manager/pkg/api/apis/operators/v1"
- olmv1alpha1 "github.com/operator-framework/operator-lifecycle-manager/pkg/api/apis/operators/v1alpha1"
- "github.com/pkg/errors"
- v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- runtime "sigs.k8s.io/controller-runtime/pkg/client"
-)
-
-// The following properties can be overridden at build time via ldflags
-
-// DefaultOperatorName is the Camel K operator name in OLM
-var DefaultOperatorName = "camel-k-operator"
-
-// DefaultPackage is the Camel K package in OLM
-var DefaultPackage = "camel-k"
-
-// DefaultChannel is the distribution channel in Operator Hub
-var DefaultChannel = "alpha"
-
-// DefaultSource is the name of the operator source where the operator is published
-var DefaultSource = "community-operators"
-
-// DefaultSourceNamespace is the namespace of the operator source
-var DefaultSourceNamespace = "openshift-marketplace"
-
-// DefaultStartingCSV contains the specific version to install
-var DefaultStartingCSV = ""
-
-// DefaultGlobalNamespace indicates a namespace containing an OperatorGroup that enables the operator to watch all namespaces.
-// It will be used in global installation mode.
-var DefaultGlobalNamespace = "openshift-operators"
-
-// Options contains information about an operator in OLM
-type Options struct {
- OperatorName string
- Package string
- Channel string
- Source string
- SourceNamespace string
- StartingCSV string
- GlobalNamespace string
-}
-
-// IsOperatorInstalled tells if a OLM CSV or a Subscription is already installed in the namespace
-func IsOperatorInstalled(ctx context.Context, client client.Client, namespace string, global bool, options Options) (bool, error) {
- options = fillDefaults(options)
- // CSV is present in current namespace for both local and global installation modes
- if csv, err := findCSV(ctx, client, namespace, options); err != nil {
- return false, err
- } else if csv != nil {
- return true, nil
- }
- // A subscription may indicate an in-progress installation
- if sub, err := findSubscription(ctx, client, namespace, global, options); err != nil {
- return false, err
- } else if sub != nil {
- return true, nil
- }
-
- return false, nil
-}
-
-// HasPermissionToInstall checks if the current user/serviceaccount has the right permissions to install camel k via OLM
-func HasPermissionToInstall(ctx context.Context, client client.Client, namespace string, global bool, options Options) (bool, error) {
- if ok, err := kubernetes.CheckPermission(client, olmv1alpha1.GroupName, "clusterserviceversions", namespace, options.Package, "list"); err != nil {
- return false, err
- } else if !ok {
- return false, nil
- }
-
- targetNamespace := namespace
- if global {
- targetNamespace = options.GlobalNamespace
- }
-
- if ok, err := kubernetes.CheckPermission(client, olmv1alpha1.GroupName, "subscriptions", targetNamespace, options.Package, "create"); err != nil {
- return false, err
- } else if !ok {
- return false, nil
- }
-
- if installed, err := IsOperatorInstalled(ctx, client, namespace, global, options); err != nil {
- return false, err
- } else if installed {
- return true, nil
- }
-
- if !global {
- if ok, err := kubernetes.CheckPermission(client, olmv1.GroupName, "operatorgroups", namespace, options.Package, "list"); err != nil {
- return false, err
- } else if !ok {
- return false, nil
- }
-
- group, err := findOperatorGroup(ctx, client, namespace, options)
- if err != nil {
- return false, err
- }
- if group == nil {
- if ok, err := kubernetes.CheckPermission(client, olmv1.GroupName, "operatorgroups", namespace, options.Package, "create"); err != nil {
- return false, err
- } else if !ok {
- return false, nil
- }
- }
-
- }
- return true, nil
-}
-
-// Install creates a subscription for the OLM package
-func Install(ctx context.Context, client client.Client, namespace string, global bool, options Options, collection *kubernetes.Collection) (bool, error) {
- options = fillDefaults(options)
- if installed, err := IsOperatorInstalled(ctx, client, namespace, global, options); err != nil {
- return false, err
- } else if installed {
- // Already installed
- return false, nil
- }
-
- targetNamespace := namespace
- if global {
- targetNamespace = options.GlobalNamespace
- }
-
- sub := olmv1alpha1.Subscription{
- ObjectMeta: v1.ObjectMeta{
- Name: options.Package,
- Namespace: targetNamespace,
- },
- Spec: &olmv1alpha1.SubscriptionSpec{
- CatalogSource: options.Source,
- CatalogSourceNamespace: options.SourceNamespace,
- Package: options.Package,
- Channel: options.Channel,
- StartingCSV: options.StartingCSV,
- InstallPlanApproval: olmv1alpha1.ApprovalAutomatic,
- },
- }
- if collection != nil {
- collection.Add(&sub)
- } else if err := client.Create(ctx, &sub); err != nil {
- return false, err
- }
-
- if !global {
- group, err := findOperatorGroup(ctx, client, namespace, options)
- if err != nil {
- return false, err
- }
- if group == nil {
- group = &olmv1.OperatorGroup{
- ObjectMeta: v1.ObjectMeta{
- Namespace: namespace,
- GenerateName: fmt.Sprintf("%s-", namespace),
- },
- Spec: olmv1.OperatorGroupSpec{
- TargetNamespaces: []string{namespace},
- },
- }
- if collection != nil {
- collection.Add(group)
- } else if err := client.Create(ctx, group); err != nil {
- return false, errors.Wrap(err, fmt.Sprintf("namespace %s has no operator group defined and "+
- "current user is not able to create it. "+
- "Make sure you have the right roles to install operators from OLM", namespace))
- }
- }
- }
- return true, nil
-}
-
-// Uninstall removes CSV and subscription from the namespace
-func Uninstall(ctx context.Context, client client.Client, namespace string, global bool, options Options) error {
- sub, err := findSubscription(ctx, client, namespace, global, options)
- if err != nil {
- return err
- }
- if sub != nil {
- if err := client.Delete(ctx, sub); err != nil {
- return err
- }
- }
-
- csv, err := findCSV(ctx, client, namespace, options)
- if err != nil {
- return err
- }
- if csv != nil {
- if err := client.Delete(ctx, csv); err != nil {
- return err
- }
- }
- return nil
-}
-
-func findSubscription(ctx context.Context, client client.Client, namespace string, global bool, options Options) (*olmv1alpha1.Subscription, error) {
- subNamespace := namespace
- if global {
- // In case of global installation, global subscription must be removed
- subNamespace = options.GlobalNamespace
- }
- subscriptionList := olmv1alpha1.SubscriptionList{}
- if err := client.List(ctx, &subscriptionList, runtime.InNamespace(subNamespace)); err != nil {
- return nil, err
- }
-
- for _, item := range subscriptionList.Items {
- if item.Spec.Package == options.Package {
- return &item, nil
- }
- }
- return nil, nil
-}
-
-func findCSV(ctx context.Context, client client.Client, namespace string, options Options) (*olmv1alpha1.ClusterServiceVersion, error) {
- csvList := olmv1alpha1.ClusterServiceVersionList{}
- if err := client.List(ctx, &csvList, runtime.InNamespace(namespace)); err != nil {
- return nil, err
- }
-
- for _, item := range csvList.Items {
- if strings.HasPrefix(item.Name, options.OperatorName) {
- return &item, nil
- }
- }
- return nil, nil
-}
-
-// nolint:unparam
-func findOperatorGroup(ctx context.Context, client client.Client, namespace string, options Options) (*olmv1.OperatorGroup, error) {
- opGroupList := olmv1.OperatorGroupList{}
- if err := client.List(ctx, &opGroupList, runtime.InNamespace(namespace)); err != nil {
- return nil, err
- }
-
- if len(opGroupList.Items) > 0 {
- return &opGroupList.Items[0], nil
- }
-
- return nil, nil
-}
-
-func fillDefaults(o Options) Options {
- if o.OperatorName == "" {
- o.OperatorName = DefaultOperatorName
- }
- if o.Package == "" {
- o.Package = DefaultPackage
- }
- if o.Channel == "" {
- o.Channel = DefaultChannel
- }
- if o.Source == "" {
- o.Source = DefaultSource
- }
- if o.SourceNamespace == "" {
- o.SourceNamespace = DefaultSourceNamespace
- }
- if o.StartingCSV == "" {
- o.StartingCSV = DefaultStartingCSV
- }
- if o.GlobalNamespace == "" {
- o.GlobalNamespace = DefaultGlobalNamespace
- }
- return o
-}
diff --git a/pkg/util/openshift/openshift.go b/pkg/util/openshift/openshift.go
deleted file mode 100644
index 7b27ee0..0000000
--- a/pkg/util/openshift/openshift.go
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package openshift
-
-import (
- "k8s.io/apimachinery/pkg/api/errors"
- "k8s.io/client-go/kubernetes"
-)
-
-// IsOpenShift returns true if we are connected to a OpenShift cluster
-func IsOpenShift(client kubernetes.Interface) (bool, error) {
- _, err := client.Discovery().ServerResourcesForGroupVersion("image.openshift.io/v1")
- if err != nil && errors.IsNotFound(err) {
- return false, nil
- } else if err != nil {
- return false, err
- }
- return true, nil
-}
diff --git a/pkg/util/openshift/register.go b/pkg/util/openshift/register.go
deleted file mode 100644
index 1687b1f..0000000
--- a/pkg/util/openshift/register.go
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package openshift
-
-import (
- "k8s.io/apimachinery/pkg/runtime"
-
- apps "github.com/openshift/api/apps/v1"
- authorization "github.com/openshift/api/authorization/v1"
- build "github.com/openshift/api/build/v1"
- console "github.com/openshift/api/console/v1"
- image "github.com/openshift/api/image/v1"
- project "github.com/openshift/api/project/v1"
- route "github.com/openshift/api/route/v1"
- template "github.com/openshift/api/template/v1"
-
- "github.com/apache/camel-k/pkg/util/log"
-)
-
-type registerFunction func(*runtime.Scheme) error
-
-// AddToScheme adds OpenShift types to the scheme
-func AddToScheme(scheme *runtime.Scheme) error {
- var err error
-
- // Standardized groups
- err = doAdd(apps.Install, scheme, err)
- err = doAdd(template.Install, scheme, err)
- err = doAdd(image.Install, scheme, err)
- err = doAdd(route.Install, scheme, err)
- err = doAdd(build.Install, scheme, err)
- err = doAdd(authorization.Install, scheme, err)
- err = doAdd(project.Install, scheme, err)
-
- // OpenShift console API
- err = doAdd(console.Install, scheme, err)
-
- return err
-}
-
-func doAdd(addToScheme registerFunction, scheme *runtime.Scheme, err error) error {
- callErr := addToScheme(scheme)
- if callErr != nil {
- log.Error(callErr, "Error while registering OpenShift types")
- }
-
- if err == nil {
- return callErr
- }
- return err
-}
diff --git a/pkg/util/patch/patch.go b/pkg/util/patch/patch.go
deleted file mode 100644
index e0ae632..0000000
--- a/pkg/util/patch/patch.go
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package patch
-
-import (
- "reflect"
-
- jsonpatch "github.com/evanphx/json-patch"
-
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/util/json"
-)
-
-func PositiveMergePatch(source runtime.Object, target runtime.Object) ([]byte, error) {
- sourceJSON, err := json.Marshal(source)
- if err != nil {
- return nil, err
- }
-
- targetJSON, err := json.Marshal(target)
- if err != nil {
- return nil, err
- }
-
- mergePatch, err := jsonpatch.CreateMergePatch(sourceJSON, targetJSON)
- if err != nil {
- return nil, err
- }
-
- var positivePatch map[string]interface{}
- err = json.Unmarshal(mergePatch, &positivePatch)
- if err != nil {
- return nil, err
- }
-
- // The following is a work-around to remove null fields from the JSON merge patch,
- // so that values defaulted by controllers server-side are not deleted.
- // It's generally acceptable as these values are orthogonal to the values managed
- // by the traits.
- removeNilValues(reflect.ValueOf(positivePatch), reflect.Value{})
-
- // Return an empty patch if no keys remain
- if len(positivePatch) == 0 {
- return make([]byte, 0), nil
- }
-
- return json.Marshal(positivePatch)
-}
-
-func removeNilValues(v reflect.Value, parent reflect.Value) {
- for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
- v = v.Elem()
- }
- switch v.Kind() {
- case reflect.Array, reflect.Slice:
- for i := 0; i < v.Len(); i++ {
- removeNilValues(v.Index(i), v)
- }
- case reflect.Map:
- for _, k := range v.MapKeys() {
- switch c := v.MapIndex(k); {
- case !c.IsValid():
- // Skip keys previously deleted
- continue
- case c.IsNil(), c.Elem().Kind() == reflect.Map && len(c.Elem().MapKeys()) == 0:
- v.SetMapIndex(k, reflect.Value{})
- default:
- removeNilValues(c, v)
- }
- }
- // Back process the parent map in case it has been emptied so that it's deleted as well
- if len(v.MapKeys()) == 0 && parent.Kind() == reflect.Map {
- removeNilValues(parent, reflect.Value{})
- }
- }
-}
diff --git a/pkg/util/registry/registry.go b/pkg/util/registry/registry.go
deleted file mode 100644
index a178d73..0000000
--- a/pkg/util/registry/registry.go
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package registry
-
-import (
- "encoding/base64"
- "encoding/json"
- "errors"
- "fmt"
-)
-
-var (
- knownServersByRegistry = map[string]string{
- "docker.io": "https://index.docker.io/v1/",
- }
-)
-
-// Auth contains basic information for authenticating against a container registry
-type Auth struct {
- Server string
- Username string
- Password string
-
- // additional information
- Registry string
-}
-
-type dockerConfigList struct {
- Auths map[string]dockerConfig `json:"auths,omitempty"`
-}
-
-type dockerConfig struct {
- Auth string `json:"auth,omitempty"`
-}
-
-// IsSet returns if information has been set on the object
-func (a Auth) IsSet() bool {
- return a.Server != "" ||
- a.Username != "" ||
- a.Password != ""
-}
-
-// validate checks if all fields are populated correctly
-func (a Auth) validate() error {
- if a.getActualServer() == "" || a.Username == "" {
- return errors.New("not enough information to generate a registry authentication file")
- }
- return nil
-}
-
-// GenerateDockerConfig generates a Docker compatible config.json file
-func (a Auth) GenerateDockerConfig() ([]byte, error) {
- if err := a.validate(); err != nil {
- return nil, err
- }
- content := a.generateDockerConfigObject()
- return json.Marshal(content)
-}
-
-func (a Auth) generateDockerConfigObject() dockerConfigList {
- return dockerConfigList{
- map[string]dockerConfig{
- a.getActualServer(): {
- a.encodedCredentials(),
- },
- },
- }
-}
-
-func (a Auth) getActualServer() string {
- if a.Server != "" {
- return a.Server
- }
- if p, ok := knownServersByRegistry[a.Registry]; ok {
- return p
- }
- return a.Registry
-}
-
-func (a Auth) encodedCredentials() string {
- return base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", a.Username, a.Password)))
-}
diff --git a/pkg/util/registry/registry_test.go b/pkg/util/registry/registry_test.go
deleted file mode 100644
index 166d87c..0000000
--- a/pkg/util/registry/registry_test.go
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package registry
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestAuth_GenerateDockerConfig(t *testing.T) {
- a := Auth{
- Username: "nic",
- Registry: "docker.io",
- }
- conf, err := a.GenerateDockerConfig()
- assert.Nil(t, err)
- assert.Equal(t, `{"auths":{"https://index.docker.io/v1/":{"auth":"bmljOg=="}}}`, string(conf))
-
- a = Auth{
- Username: "nic",
- Password: "pass",
- Registry: "quay.io",
- }
- conf, err = a.GenerateDockerConfig()
- assert.Nil(t, err)
- assert.Equal(t, `{"auths":{"quay.io":{"auth":"bmljOnBhc3M="}}}`, string(conf))
-
- a = Auth{
- Username: "nic",
- Password: "pass",
- Server: "quay.io",
- Registry: "docker.io",
- }
- conf, err = a.GenerateDockerConfig()
- assert.Nil(t, err)
- assert.Equal(t, `{"auths":{"quay.io":{"auth":"bmljOnBhc3M="}}}`, string(conf))
-}
-
-func TestAuth_Validate(t *testing.T) {
- assert.NotNil(t, Auth{
- Username: "nic",
- }.validate())
-
- assert.NotNil(t, Auth{
- Server: "quay.io",
- }.validate())
-
- assert.Nil(t, Auth{
- Username: "nic",
- Server: "quay.io",
- }.validate())
-}
diff --git a/pkg/util/source/inspector.go b/pkg/util/source/inspector.go
deleted file mode 100644
index 25347d3..0000000
--- a/pkg/util/source/inspector.go
+++ /dev/null
@@ -1,320 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package source
-
-import (
- "fmt"
- "regexp"
- "strings"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/util"
- "github.com/apache/camel-k/pkg/util/camel"
-)
-
-type catalog2deps func(*camel.RuntimeCatalog) []string
-
-var (
- singleQuotedFrom = regexp.MustCompile(`from\s*\(\s*'([a-zA-Z0-9-]+:[^']+)'`)
- doubleQuotedFrom = regexp.MustCompile(`from\s*\(\s*"([a-zA-Z0-9-]+:[^"]+)"`)
- singleQuotedTo = regexp.MustCompile(`\.to\s*\(\s*'([a-zA-Z0-9-]+:[^']+)'`)
- singleQuotedToD = regexp.MustCompile(`\.toD\s*\(\s*'([a-zA-Z0-9-]+:[^']+)'`)
- singleQuotedToF = regexp.MustCompile(`\.toF\s*\(\s*'([a-zA-Z0-9-]+:[^']+)'`)
- doubleQuotedTo = regexp.MustCompile(`\.to\s*\(\s*"([a-zA-Z0-9-]+:[^"]+)"`)
- doubleQuotedToD = regexp.MustCompile(`\.toD\s*\(\s*"([a-zA-Z0-9-]+:[^"]+)"`)
- doubleQuotedToF = regexp.MustCompile(`\.toF\s*\(\s*"([a-zA-Z0-9-]+:[^"]+)"`)
- languageRegexp = regexp.MustCompile(`language\s*\(\s*["|']([a-zA-Z0-9-]+[^"|']+)["|']\s*,.*\)`)
- camelTypeRegexp = regexp.MustCompile(`.*(org.apache.camel.*Component|DataFormat|Language)`)
- jsonLibraryRegexp = regexp.MustCompile(`.*JsonLibrary\.Jackson.*`)
- jsonLanguageRegexp = regexp.MustCompile(`.*\.json\(\).*`)
- circuitBreakerRegexp = regexp.MustCompile(`.*\.circuitBreaker\(\).*`)
- restConfigurationRegexp = regexp.MustCompile(`.*restConfiguration\(\).*`)
- restRegexp = regexp.MustCompile(`.*rest\s*\([^)]*\).*`)
- restClosureRegexp = regexp.MustCompile(`.*rest\s*{\s*`)
- groovyLanguageRegexp = regexp.MustCompile(`.*\.groovy\s*\(.*\).*`)
- jsonPathLanguageRegexp = regexp.MustCompile(`.*\.?(jsonpath|jsonpathWriteAsString)\s*\(.*\).*`)
- ognlRegexp = regexp.MustCompile(`.*\.ognl\s*\(.*\).*`)
- mvelRegexp = regexp.MustCompile(`.*\.mvel\s*\(.*\).*`)
- xqueryRegexp = regexp.MustCompile(`.*\.xquery\s*\(.*\).*`)
- xpathRegexp = regexp.MustCompile(`.*\.?xpath\s*\(.*\).*`)
- xtokenizeRegexp = regexp.MustCompile(`.*\.xtokenize\s*\(.*\).*`)
-
- sourceDependencies = map[*regexp.Regexp]catalog2deps{
- jsonLibraryRegexp: func(_ *camel.RuntimeCatalog) []string {
- return []string{"camel:jackson"}
- },
- jsonLanguageRegexp: func(_ *camel.RuntimeCatalog) []string {
- return []string{"camel:jackson"}
- },
- circuitBreakerRegexp: func(_ *camel.RuntimeCatalog) []string {
- return []string{"camel:hystrix"}
- },
- restConfigurationRegexp: func(catalog *camel.RuntimeCatalog) []string {
- deps := make([]string, 0)
- if c, ok := catalog.CamelCatalogSpec.Runtime.Capabilities["rest"]; ok {
- for _, d := range c.Dependencies {
- deps = append(deps, fmt.Sprintf("mvn:%s/%s", d.GroupID, d.ArtifactID))
- }
- }
- return deps
- },
- restRegexp: func(catalog *camel.RuntimeCatalog) []string {
- deps := make([]string, 0)
- if c, ok := catalog.CamelCatalogSpec.Runtime.Capabilities["rest"]; ok {
- for _, d := range c.Dependencies {
- deps = append(deps, fmt.Sprintf("mvn:%s/%s", d.GroupID, d.ArtifactID))
- }
- }
- return deps
- },
- restClosureRegexp: func(catalog *camel.RuntimeCatalog) []string {
- deps := make([]string, 0)
- if c, ok := catalog.CamelCatalogSpec.Runtime.Capabilities["rest"]; ok {
- for _, d := range c.Dependencies {
- deps = append(deps, fmt.Sprintf("mvn:%s/%s", d.GroupID, d.ArtifactID))
- }
- }
- return deps
- },
- groovyLanguageRegexp: func(catalog *camel.RuntimeCatalog) []string {
- if dependency, ok := catalog.GetLanguageDependency("groovy"); ok {
- return []string{dependency}
- }
-
- return []string{}
- },
- jsonPathLanguageRegexp: func(catalog *camel.RuntimeCatalog) []string {
- if dependency, ok := catalog.GetLanguageDependency("jsonpath"); ok {
- return []string{dependency}
- }
-
- return []string{}
- },
- ognlRegexp: func(catalog *camel.RuntimeCatalog) []string {
- if dependency, ok := catalog.GetLanguageDependency("ognl"); ok {
- return []string{dependency}
- }
-
- return []string{}
- },
- mvelRegexp: func(catalog *camel.RuntimeCatalog) []string {
- if dependency, ok := catalog.GetLanguageDependency("mvel"); ok {
- return []string{dependency}
- }
-
- return []string{}
- },
- xqueryRegexp: func(catalog *camel.RuntimeCatalog) []string {
- if dependency, ok := catalog.GetLanguageDependency("xquery"); ok {
- return []string{dependency}
- }
-
- return []string{}
- },
- xpathRegexp: func(catalog *camel.RuntimeCatalog) []string {
- if dependency, ok := catalog.GetLanguageDependency("xpath"); ok {
- return []string{dependency}
- }
-
- return []string{}
- },
- xtokenizeRegexp: func(catalog *camel.RuntimeCatalog) []string {
- if dependency, ok := catalog.GetLanguageDependency("xtokenize"); ok {
- return []string{dependency}
- }
-
- return []string{}
- },
- }
-)
-
-// Inspector --
-type Inspector interface {
- Extract(v1.SourceSpec, *Metadata) error
-}
-
-// InspectorForLanguage --
-func InspectorForLanguage(catalog *camel.RuntimeCatalog, language v1.Language) Inspector {
- switch language {
- case v1.LanguageJavaSource:
- return &JavaSourceInspector{
- baseInspector: baseInspector{
- catalog: catalog,
- },
- }
- case v1.LanguageXML:
- return &XMLInspector{
- baseInspector: baseInspector{
- catalog: catalog,
- },
- }
- case v1.LanguageGroovy:
- return &GroovyInspector{
- baseInspector: baseInspector{
- catalog: catalog,
- },
- }
- case v1.LanguageJavaScript:
- return &JavaScriptInspector{
- baseInspector: baseInspector{
- catalog: catalog,
- },
- }
- case v1.LanguageKotlin:
- return &KotlinInspector{
- baseInspector: baseInspector{
- catalog: catalog,
- },
- }
- case v1.LanguageYaml:
- return &YAMLInspector{
- baseInspector: baseInspector{
- catalog: catalog,
- },
- }
- }
- return &baseInspector{}
-}
-
-type baseInspector struct {
- catalog *camel.RuntimeCatalog
-}
-
-func (i baseInspector) Extract(v1.SourceSpec, *Metadata) error {
- return nil
-}
-
-// discoverDependencies returns a list of dependencies required by the given source code
-func (i *baseInspector) discoverCapabilities(_ v1.SourceSpec, meta *Metadata) {
- uris := util.StringSliceJoin(meta.FromURIs, meta.ToURIs)
-
- for _, uri := range uris {
- if i.getURIPrefix(uri) == "platform-http" {
- meta.RequiredCapabilities.Add(v1.CapabilityPlatformHTTP)
- }
- }
-}
-
-// discoverDependencies returns a list of dependencies required by the given source code
-func (i *baseInspector) discoverDependencies(source v1.SourceSpec, meta *Metadata) {
- uris := util.StringSliceJoin(meta.FromURIs, meta.ToURIs)
-
- for _, uri := range uris {
- candidateComp := i.decodeComponent(uri)
- if candidateComp != "" {
- i.addDependency(candidateComp, meta)
- }
- }
-
- for pattern, supplier := range sourceDependencies {
- if !pattern.MatchString(source.Content) {
- continue
- }
-
- for _, dep := range supplier(i.catalog) {
- i.addDependency(dep, meta)
- }
- }
-
- for _, match := range languageRegexp.FindAllStringSubmatch(source.Content, -1) {
- if len(match) > 1 {
- if dependency, ok := i.catalog.GetLanguageDependency(match[1]); ok {
- i.addDependency(dependency, meta)
- }
- }
- }
-
- for _, match := range camelTypeRegexp.FindAllStringSubmatch(source.Content, -1) {
- if len(match) > 1 {
- if dependency, ok := i.catalog.GetJavaTypeDependency(match[1]); ok {
- i.addDependency(dependency, meta)
- }
- }
- }
-}
-
-func (i *baseInspector) addDependency(dependency string, meta *Metadata) {
- if i.catalog.Runtime.Provider == v1.RuntimeProviderQuarkus {
- if strings.HasPrefix(dependency, "camel:") {
- dependency = "camel-quarkus:" + strings.TrimPrefix(dependency, "camel:")
- }
- }
- meta.Dependencies.Add(dependency)
-}
-
-func (i *baseInspector) decodeComponent(uri string) string {
- uriSplit := strings.SplitN(uri, ":", 2)
- if len(uriSplit) < 2 {
- return ""
- }
- uriStart := uriSplit[0]
- if component := i.catalog.GetArtifactByScheme(uriStart); component != nil {
- return component.GetDependencyID()
- }
- return ""
-}
-
-// hasOnlyPassiveEndpoints returns true if the source has no endpoint that needs to remain always active
-func (i *baseInspector) hasOnlyPassiveEndpoints(fromURIs []string) bool {
- passivePlusHTTP := make(map[string]bool)
- i.catalog.VisitSchemes(func(id string, scheme v1.CamelScheme) bool {
- if scheme.HTTP || scheme.Passive {
- passivePlusHTTP[id] = true
- }
-
- return true
- })
-
- return i.containsOnlyURIsIn(fromURIs, passivePlusHTTP)
-}
-
-func (i *baseInspector) containsOnlyURIsIn(fromURI []string, allowed map[string]bool) bool {
- for _, uri := range fromURI {
- prefix := i.getURIPrefix(uri)
- if enabled, ok := allowed[prefix]; !ok || !enabled {
- return false
- }
- }
- return true
-}
-
-func (i *baseInspector) getURIPrefix(uri string) string {
- parts := strings.SplitN(uri, ":", 2)
- if len(parts) > 0 {
- return parts[0]
- }
- return ""
-}
-
-func (i *baseInspector) containsHTTPURIs(fromURI []string) bool {
- for _, uri := range fromURI {
- prefix := i.getURIPrefix(uri)
- scheme, ok := i.catalog.GetScheme(prefix)
-
- if !ok {
- // scheme does not exists
- continue
- }
-
- if scheme.HTTP {
- return true
- }
- }
-
- return false
-}
diff --git a/pkg/util/source/inspector_groovy.go b/pkg/util/source/inspector_groovy.go
deleted file mode 100644
index b6db6e9..0000000
--- a/pkg/util/source/inspector_groovy.go
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package source
-
-import (
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/util"
-)
-
-// GroovyInspector --
-type GroovyInspector struct {
- baseInspector
-}
-
-// Extract --
-func (i GroovyInspector) Extract(source v1.SourceSpec, meta *Metadata) error {
- from := util.FindAllDistinctStringSubmatch(
- source.Content,
- singleQuotedFrom,
- doubleQuotedFrom,
- )
- to := util.FindAllDistinctStringSubmatch(
- source.Content,
- singleQuotedTo,
- doubleQuotedTo,
- singleQuotedToD,
- doubleQuotedToD,
- singleQuotedToF,
- doubleQuotedToF,
- )
-
- meta.FromURIs = append(meta.FromURIs, from...)
- meta.ToURIs = append(meta.ToURIs, to...)
-
- i.discoverCapabilities(source, meta)
- i.discoverDependencies(source, meta)
-
- hasRest := restRegexp.MatchString(source.Content) || restClosureRegexp.MatchString(source.Content)
- if hasRest {
- meta.RequiredCapabilities.Add(v1.CapabilityRest)
- }
-
- meta.ExposesHTTPServices = hasRest || i.containsHTTPURIs(meta.FromURIs)
- meta.PassiveEndpoints = i.hasOnlyPassiveEndpoints(meta.FromURIs)
-
- return nil
-}
diff --git a/pkg/util/source/inspector_java_script.go b/pkg/util/source/inspector_java_script.go
deleted file mode 100644
index 00dba9a..0000000
--- a/pkg/util/source/inspector_java_script.go
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package source
-
-import (
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/util"
-)
-
-// JavaScriptInspector --
-type JavaScriptInspector struct {
- baseInspector
-}
-
-// Extract --
-func (i JavaScriptInspector) Extract(source v1.SourceSpec, meta *Metadata) error {
- from := util.FindAllDistinctStringSubmatch(
- source.Content,
- singleQuotedFrom,
- doubleQuotedFrom,
- )
- to := util.FindAllDistinctStringSubmatch(
- source.Content,
- singleQuotedTo,
- doubleQuotedTo,
- singleQuotedToD,
- doubleQuotedToD,
- singleQuotedToF,
- doubleQuotedToF,
- )
-
- meta.FromURIs = append(meta.FromURIs, from...)
- meta.ToURIs = append(meta.ToURIs, to...)
-
- i.discoverCapabilities(source, meta)
- i.discoverDependencies(source, meta)
-
- hasRest := restRegexp.MatchString(source.Content)
- if hasRest {
- meta.RequiredCapabilities.Add(v1.CapabilityRest)
- }
-
- meta.ExposesHTTPServices = hasRest || i.containsHTTPURIs(meta.FromURIs)
- meta.PassiveEndpoints = i.hasOnlyPassiveEndpoints(meta.FromURIs)
-
- return nil
-}
diff --git a/pkg/util/source/inspector_java_source.go b/pkg/util/source/inspector_java_source.go
deleted file mode 100644
index 6e0386f..0000000
--- a/pkg/util/source/inspector_java_source.go
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package source
-
-import (
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/util"
-)
-
-// JavaSourceInspector --
-type JavaSourceInspector struct {
- baseInspector
-}
-
-// Extract --
-func (i JavaSourceInspector) Extract(source v1.SourceSpec, meta *Metadata) error {
- from := util.FindAllDistinctStringSubmatch(
- source.Content,
- doubleQuotedFrom,
- )
- to := util.FindAllDistinctStringSubmatch(
- source.Content,
- doubleQuotedTo,
- doubleQuotedToD,
- doubleQuotedToF,
- )
-
- meta.FromURIs = append(meta.FromURIs, from...)
- meta.ToURIs = append(meta.ToURIs, to...)
-
- i.discoverCapabilities(source, meta)
- i.discoverDependencies(source, meta)
-
- hasRest := restRegexp.MatchString(source.Content)
- if hasRest {
- meta.RequiredCapabilities.Add(v1.CapabilityRest)
- }
-
- meta.ExposesHTTPServices = hasRest || i.containsHTTPURIs(meta.FromURIs)
- meta.PassiveEndpoints = i.hasOnlyPassiveEndpoints(meta.FromURIs)
-
- return nil
-}
diff --git a/pkg/util/source/inspector_kotlin.go b/pkg/util/source/inspector_kotlin.go
deleted file mode 100644
index 7dab24a..0000000
--- a/pkg/util/source/inspector_kotlin.go
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package source
-
-import (
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/util"
-)
-
-// KotlinInspector --
-type KotlinInspector struct {
- baseInspector
-}
-
-// Extract --
-func (i KotlinInspector) Extract(source v1.SourceSpec, meta *Metadata) error {
- from := util.FindAllDistinctStringSubmatch(
- source.Content,
- doubleQuotedFrom,
- )
- to := util.FindAllDistinctStringSubmatch(
- source.Content,
- doubleQuotedTo,
- doubleQuotedToD,
- doubleQuotedToF,
- )
-
- meta.FromURIs = append(meta.FromURIs, from...)
- meta.ToURIs = append(meta.ToURIs, to...)
-
- i.discoverCapabilities(source, meta)
- i.discoverDependencies(source, meta)
-
- hasRest := restRegexp.MatchString(source.Content) || restClosureRegexp.MatchString(source.Content)
- if hasRest {
- meta.RequiredCapabilities.Add(v1.CapabilityRest)
- }
-
- meta.ExposesHTTPServices = hasRest || i.containsHTTPURIs(meta.FromURIs)
- meta.PassiveEndpoints = i.hasOnlyPassiveEndpoints(meta.FromURIs)
-
- return nil
-}
diff --git a/pkg/util/source/inspector_xml.go b/pkg/util/source/inspector_xml.go
deleted file mode 100644
index 4d4f39e..0000000
--- a/pkg/util/source/inspector_xml.go
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package source
-
-import (
- "encoding/xml"
- "strings"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
-)
-
-// XMLInspector --
-type XMLInspector struct {
- baseInspector
-}
-
-// Extract --
-func (i XMLInspector) Extract(source v1.SourceSpec, meta *Metadata) error {
- content := strings.NewReader(source.Content)
- decoder := xml.NewDecoder(content)
-
- for {
- // Read tokens from the XML document in a stream.
- t, _ := decoder.Token()
- if t == nil {
- break
- }
-
- if se, ok := t.(xml.StartElement); ok {
- switch se.Name.Local {
- case "rest", "restConfiguration":
- meta.ExposesHTTPServices = true
- meta.RequiredCapabilities.Add(v1.CapabilityRest)
- case "circuitBreaker":
- i.addDependency("camel:hystrix", meta)
- case "language":
- for _, a := range se.Attr {
- if a.Name.Local == "language" {
- if dependency, ok := i.catalog.GetLanguageDependency(a.Value); ok {
- i.addDependency(dependency, meta)
- }
- }
- }
- case "from", "fromF":
- for _, a := range se.Attr {
- if a.Name.Local == "uri" {
- meta.FromURIs = append(meta.FromURIs, a.Value)
- }
- }
- case "to", "toD", "toF":
- for _, a := range se.Attr {
- if a.Name.Local == "uri" {
- meta.ToURIs = append(meta.ToURIs, a.Value)
- }
- }
- }
-
- if dependency, ok := i.catalog.GetLanguageDependency(se.Name.Local); ok {
- i.addDependency(dependency, meta)
- }
- }
- }
-
- i.discoverCapabilities(source, meta)
- i.discoverDependencies(source, meta)
-
- meta.ExposesHTTPServices = meta.ExposesHTTPServices || i.containsHTTPURIs(meta.FromURIs)
- meta.PassiveEndpoints = i.hasOnlyPassiveEndpoints(meta.FromURIs)
-
- return nil
-}
diff --git a/pkg/util/source/inspector_yaml.go b/pkg/util/source/inspector_yaml.go
deleted file mode 100644
index f705b62..0000000
--- a/pkg/util/source/inspector_yaml.go
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package source
-
-import (
- "fmt"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- yaml2 "gopkg.in/yaml.v2"
-)
-
-// YAMLInspector --
-type YAMLInspector struct {
- baseInspector
-}
-
-// Extract --
-func (i YAMLInspector) Extract(source v1.SourceSpec, meta *Metadata) error {
- definitions := make([]map[string]interface{}, 0)
-
- if err := yaml2.Unmarshal([]byte(source.Content), &definitions); err != nil {
- return err
- }
-
- for _, definition := range definitions {
- for k, v := range definition {
- if err := i.parseStep(k, v, meta); err != nil {
- return err
- }
- }
- }
-
- i.discoverCapabilities(source, meta)
- i.discoverDependencies(source, meta)
-
- meta.ExposesHTTPServices = meta.ExposesHTTPServices || i.containsHTTPURIs(meta.FromURIs)
- meta.PassiveEndpoints = i.hasOnlyPassiveEndpoints(meta.FromURIs)
-
- return nil
-}
-
-func (i YAMLInspector) parseStep(key string, content interface{}, meta *Metadata) error {
- switch key {
- case "rest":
- meta.ExposesHTTPServices = true
- meta.RequiredCapabilities.Add(v1.CapabilityRest)
- case "circuitBreaker":
- i.addDependency("camel:hystrix", meta)
- }
-
- var maybeURI string
-
- switch t := content.(type) {
- case string:
- maybeURI = t
- case map[interface{}]interface{}:
- if u, ok := t["rest"]; ok {
- return i.parseStep("rest", u, meta)
- } else if u, ok := t["from"]; ok {
- return i.parseStep("from", u, meta)
- } else if u, ok := t["steps"]; ok {
- steps := u.([]interface{})
-
- for _, raw := range steps {
- step := raw.(map[interface{}]interface{})
-
- if len(step) != 1 {
- return fmt.Errorf("unable to parse step: %v", step)
- }
-
- for k, v := range step {
- switch kt := k.(type) {
- case fmt.Stringer:
- if err := i.parseStep(kt.String(), v, meta); err != nil {
- return err
- }
- case string:
- if err := i.parseStep(kt, v, meta); err != nil {
- return err
- }
- default:
- return fmt.Errorf("unknown key type: %v, step: %v", k, step)
- }
- }
- }
- }
-
- if u, ok := t["uri"]; ok {
- maybeURI = u.(string)
- }
-
- if _, ok := t["language"]; ok {
- if s, ok := t["language"].(string); ok {
- if dependency, ok := i.catalog.GetLanguageDependency(s); ok {
- i.addDependency(dependency, meta)
- }
- } else if m, ok := t["language"].(map[interface{}]interface{}); ok {
- if err := i.parseStep("language", m, meta); err != nil {
- return err
- }
- }
- }
-
- for k := range t {
- if s, ok := k.(string); ok {
- if dependency, ok := i.catalog.GetLanguageDependency(s); ok {
- i.addDependency(dependency, meta)
- }
- }
- }
- }
-
- if maybeURI != "" {
- switch key {
- case "from":
- meta.FromURIs = append(meta.FromURIs, maybeURI)
- case "to":
- meta.ToURIs = append(meta.ToURIs, maybeURI)
- }
- }
- return nil
-}
diff --git a/pkg/util/source/inspector_yaml_test.go b/pkg/util/source/inspector_yaml_test.go
deleted file mode 100644
index 2d5db00..0000000
--- a/pkg/util/source/inspector_yaml_test.go
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package source
-
-import (
- "testing"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/util/camel"
- "github.com/stretchr/testify/assert"
-)
-
-func NewtestYAMLInspector(t *testing.T) YAMLInspector {
- catalog, err := camel.DefaultCatalog()
- assert.Nil(t, err)
-
- return YAMLInspector{
- baseInspector: baseInspector{
- catalog: catalog,
- },
- }
-}
-
-const YAMLRestDSL = `
-- rest:
- verb: "post"
- uri: "/api/flow"
- accepts: "text/plain"
- binding-mode: "off"
- steps:
- - convert-body:
- type: "java.lang.String"
- - to:
- uri: "log:in"
- - filter:
- simple: "${body.contains(\",\")}"
- - split:
- tokenize: ";"
- - set-body:
- simple: "${body.toLowerCase()}"
- - to:
- uri: "log:out"
-`
-
-const YAMLRestDSLWithRoute = `
-- route:
- id: "flow"
- group: "routes"
- rest:
- verb: "post"
- uri: "/api/flow"
- accepts: "text/plain"
- binding-mode: "off"
- steps:
- - convert-body:
- type: "java.lang.String"
- - to:
- uri: "log:in"
- - filter:
- simple: "${body.contains(\",\")}"
- - split:
- tokenize: ";"
- - set-body:
- simple: "${body.toLowerCase()}"
- - to:
- uri: "log:out"
-`
-
-func TestYAMLRestDSL(t *testing.T) {
- for name, content := range map[string]string{"YAMLRestDSL": YAMLRestDSL, "YAMLRestDSLWithRoute": YAMLRestDSLWithRoute} {
- sourceContent := content
- t.Run(name, func(t *testing.T) {
- code := v1.SourceSpec{
- DataSpec: v1.DataSpec{
- Name: "route.yaml",
- Content: sourceContent,
- },
- Language: v1.LanguageYaml,
- }
-
- meta := NewMetadata()
- inspector := NewtestYAMLInspector(t)
-
- err := inspector.Extract(code, &meta)
- assert.Nil(t, err)
- assert.True(t, meta.RequiredCapabilities.Has(v1.CapabilityRest))
- assert.True(t, meta.Dependencies.Has("camel:log"))
- assert.True(t, meta.ExposesHTTPServices)
- })
- }
-}
diff --git a/pkg/util/source/types.go b/pkg/util/source/types.go
deleted file mode 100644
index f6f15e0..0000000
--- a/pkg/util/source/types.go
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package source
-
-import "github.com/scylladb/go-set/strset"
-
-// Metadata --
-type Metadata struct {
- // All starting URIs of defined routes
- FromURIs []string
- // All end URIs of defined routes
- ToURIs []string
- // All inferred dependencies required to run the integration
- Dependencies *strset.Set
- // ExposesHTTPServices indicates if a route defined by the source is exposed
- // through HTTP
- ExposesHTTPServices bool
- // PassiveEndpoints indicates that the source contains only passive endpoints that
- // are activated from external calls, including HTTP (useful to determine if the
- // integration can scale to 0)
- PassiveEndpoints bool
- // RequiredCapabilities lists the capabilities required by the integration
- // to run
- RequiredCapabilities *strset.Set
-}
-
-// NewMetadata --
-func NewMetadata() Metadata {
- return Metadata{
- FromURIs: make([]string, 0),
- ToURIs: make([]string, 0),
- Dependencies: strset.New(),
- RequiredCapabilities: strset.New(),
- }
-}
diff --git a/pkg/util/sync/file.go b/pkg/util/sync/file.go
deleted file mode 100644
index f362d04..0000000
--- a/pkg/util/sync/file.go
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-// Package sync provides useful tools to get notified when a file system resource changes
-package sync
-
-import (
- "context"
- "time"
-
- "github.com/apache/camel-k/pkg/util/log"
- "github.com/radovskyb/watcher"
-)
-
-// File returns a channel that signals each time the content of the file changes
-func File(ctx context.Context, path string) (<-chan bool, error) {
- w := watcher.New()
- if err := w.Add(path); err != nil {
- return nil, err
- }
- w.FilterOps(watcher.Write)
-
- out := make(chan bool)
- go func() {
- for {
- select {
- case <-ctx.Done():
- return
- case <-w.Event:
- out <- true
- }
- }
- }()
-
- go func() {
- if err := w.Start(200 * time.Millisecond); err != nil {
- log.Error(err, "Error while starting watcher")
- close(out)
- }
- }()
-
- return out, nil
-}
diff --git a/pkg/util/sync/file_test.go b/pkg/util/sync/file_test.go
deleted file mode 100644
index 1b665c8..0000000
--- a/pkg/util/sync/file_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package sync
-
-import (
- "context"
- "io/ioutil"
- "math/rand"
- "os"
- "path"
- "strconv"
- "testing"
- "time"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestFile(t *testing.T) {
- tempdir := os.TempDir()
- fileName := path.Join(tempdir, "camel-k-test-"+strconv.FormatUint(rand.Uint64(), 10))
- _, err := os.Create(fileName)
- assert.Nil(t, err)
- defer os.Remove(fileName)
-
- ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(100*time.Second))
- defer cancel()
- changes, err := File(ctx, fileName)
- assert.Nil(t, err)
-
- time.Sleep(100 * time.Millisecond)
- expectedNumChanges := 3
- for i := 0; i < expectedNumChanges; i++ {
- if err := ioutil.WriteFile(fileName, []byte("data-"+strconv.Itoa(i)), 0777); err != nil {
- t.Error(err)
- }
- time.Sleep(350 * time.Millisecond)
- }
-
- numChanges := 0
-watch:
- for {
- select {
- case <-ctx.Done():
- return
- case <-changes:
- numChanges++
- if numChanges == expectedNumChanges {
- break watch
- }
- }
- }
-
- assert.Equal(t, expectedNumChanges, numChanges)
-}
diff --git a/pkg/util/test/assertions.go b/pkg/util/test/assertions.go
deleted file mode 100644
index 4df8f9c..0000000
--- a/pkg/util/test/assertions.go
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package test
-
-import (
- "testing"
-
- "github.com/apache/camel-k/pkg/util/envvar"
- "github.com/stretchr/testify/assert"
-
- corev1 "k8s.io/api/core/v1"
-)
-
-// EnvVarExists --
-func EnvVarExists(t *testing.T, env []corev1.EnvVar, name string) {
- ev := envvar.Get(env, name)
- assert.NotNil(t, ev)
-}
-
-// EnvVarHasValue --
-func EnvVarHasValue(t *testing.T, env []corev1.EnvVar, name string, val string) {
- ev := envvar.Get(env, name)
- assert.NotNil(t, ev)
- assert.Equal(t, val, ev.Value)
-}
-
-// HasVolume --
-func HasVolume(t *testing.T, volumes []corev1.Volume, name string) {
- assert.Condition(t, func() bool {
- for _, v := range volumes {
- if v.Name == name {
- return true
- }
- }
- return false
- })
-}
diff --git a/pkg/util/test/catalog_test.go b/pkg/util/test/catalog_test.go
deleted file mode 100644
index 9e483f4..0000000
--- a/pkg/util/test/catalog_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package test
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-
- "github.com/apache/camel-k/pkg/util/camel"
- "github.com/apache/camel-k/pkg/util/defaults"
-)
-
-func TestRuntimeContainsEmbeddedArtifacts(t *testing.T) {
- catalog, err := camel.DefaultCatalog()
- assert.Nil(t, err)
-
- assert.Equal(t, defaults.DefaultRuntimeVersion, catalog.Runtime.Version)
-
- artifact := catalog.GetArtifactByScheme("knative")
- assert.Equal(t, 1, len(artifact.Schemes))
- assert.Equal(t, "org.apache.camel.k", artifact.GroupID)
- assert.Equal(t, "camel-knative", artifact.ArtifactID)
-
- scheme, found := catalog.GetScheme("knative")
- assert.True(t, found)
- assert.True(t, scheme.HTTP)
-}
diff --git a/pkg/util/test/client.go b/pkg/util/test/client.go
deleted file mode 100644
index d3df07b..0000000
--- a/pkg/util/test/client.go
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package test
-
-import (
- "github.com/apache/camel-k/pkg/apis"
- "github.com/apache/camel-k/pkg/client"
-
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/client-go/kubernetes"
- clientscheme "k8s.io/client-go/kubernetes/scheme"
- "k8s.io/client-go/rest"
-
- controller "sigs.k8s.io/controller-runtime/pkg/client"
- "sigs.k8s.io/controller-runtime/pkg/client/fake"
-)
-
-// NewFakeClient ---
-func NewFakeClient(initObjs ...runtime.Object) (client.Client, error) {
- scheme := clientscheme.Scheme
-
- // Setup Scheme for all resources
- if err := apis.AddToScheme(scheme); err != nil {
- return nil, err
- }
-
- c := fake.NewFakeClientWithScheme(scheme, initObjs...)
-
- return &FakeClient{
- Client: c,
- Interface: nil,
- }, nil
-}
-
-// FakeClient ---
-type FakeClient struct {
- controller.Client
- kubernetes.Interface
-}
-
-// GetScheme ---
-func (c *FakeClient) GetScheme() *runtime.Scheme {
- return clientscheme.Scheme
-}
-
-func (c *FakeClient) GetConfig() *rest.Config {
- return nil
-}
-
-func (c *FakeClient) GetCurrentNamespace(kubeConfig string) (string, error) {
- return "", nil
-}
diff --git a/pkg/util/test/cmd.go b/pkg/util/test/cmd.go
deleted file mode 100644
index 7d7f003..0000000
--- a/pkg/util/test/cmd.go
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package test
-
-import (
- "bytes"
-
- "github.com/spf13/cobra"
-)
-
-func EmptyRun(*cobra.Command, []string) {}
-
-func ArbitraryArgs(cmd *cobra.Command, args []string) error {
- return nil
-}
-
-func ExecuteCommand(root *cobra.Command, args ...string) (output string, err error) {
- _, output, err = ExecuteCommandC(root, args...)
- return output, err
-}
-
-func ExecuteCommandC(root *cobra.Command, args ...string) (c *cobra.Command, output string, err error) {
- buf := new(bytes.Buffer)
- root.SetOut(buf)
- root.SetErr(buf)
- root.SetArgs(args)
-
- c, err = root.ExecuteC()
-
- return c, buf.String(), err
-}
diff --git a/pkg/util/uri/uri.go b/pkg/util/uri/uri.go
deleted file mode 100644
index 6e9122d..0000000
--- a/pkg/util/uri/uri.go
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package uri
-
-import (
- "fmt"
- "net/url"
- "regexp"
- "strings"
-
- "github.com/apache/camel-k/pkg/util/log"
-)
-
-var queryExtractorRegexp = `^[^?]+\?(?:|.*[&])%s=([^&]+)(?:[&].*|$)`
-
-// GetComponent returns the Camel component used in the URI
-func GetComponent(uri string) string {
- parts := strings.Split(uri, ":")
- if len(parts) <= 1 {
- return ""
- }
- return parts[0]
-}
-
-// GetQueryParameter returns the given parameter from the uri, if present
-func GetQueryParameter(uri string, param string) string {
- paramRegexp := regexp.MustCompile(fmt.Sprintf(queryExtractorRegexp, regexp.QuoteMeta(param)))
- val := matchOrEmpty(paramRegexp, uri)
- res, err := url.QueryUnescape(val)
- if err != nil {
- log.Error(err, fmt.Sprintf("Invalid character sequence in parameter %q", param))
- return ""
- }
- return res
-}
-
-func matchOrEmpty(reg *regexp.Regexp, str string) string {
- match := reg.FindStringSubmatch(str)
- if len(match) > 1 {
- return match[1]
- }
- return ""
-}
diff --git a/pkg/util/uri/uri_test.go b/pkg/util/uri/uri_test.go
deleted file mode 100644
index 8908fec..0000000
--- a/pkg/util/uri/uri_test.go
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package uri
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestQueryParameter(t *testing.T) {
- tests := []struct {
- uri string
- param string
- expected string
- component string
- }{
- {
- uri: "direct:endpoint",
- param: "notPresent",
- expected: "",
- component: "direct",
- },
- {
- uri: "knative:endpoint/channel?brokerURI=123",
- param: "brokeruri",
- expected: "",
- component: "knative",
- },
- {
- uri: "knative:endpoint/channel?brokerURI=123",
- param: "brokerURI",
- expected: "123",
- component: "knative",
- },
- {
- uri: "timer:tick?delay=123&period=3000",
- param: "period",
- expected: "3000",
- component: "timer",
- },
- {
- uri: "timer:tick?period=3000&delay=4000",
- param: "period",
- expected: "3000",
- component: "timer",
- },
- {
- uri: "timer:tick?delay=123&period=3000",
- param: ".*",
- expected: "",
- component: "timer",
- },
- {
- uri: "timer:tick?delay=123&period=3000",
- param: ".",
- expected: "",
- component: "timer",
- },
- {
- uri: "tick&delay=123&period=3000",
- param: "delay",
- expected: "",
- component: "",
- },
- }
-
- for _, test := range tests {
- thetest := test
- t.Run(thetest.uri, func(t *testing.T) {
- param := GetQueryParameter(thetest.uri, thetest.param)
- assert.Equal(t, thetest.expected, param)
- })
- }
-
-}
diff --git a/pkg/util/util.go b/pkg/util/util.go
deleted file mode 100644
index 34ac490..0000000
--- a/pkg/util/util.go
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package util
-
-import (
- "bytes"
- "encoding/xml"
- "fmt"
- "io"
- "os"
- "path"
- "regexp"
- "sort"
-
- "github.com/pkg/errors"
-
- "github.com/scylladb/go-set/strset"
-)
-
-// StringSliceJoin --
-func StringSliceJoin(slices ...[]string) []string {
- size := 0
-
- for _, s := range slices {
- size += len(s)
- }
-
- result := make([]string, 0, size)
-
- for _, s := range slices {
- result = append(result, s...)
- }
-
- return result
-}
-
-// StringSliceContains --
-func StringSliceContains(slice []string, items []string) bool {
- for i := 0; i < len(items); i++ {
- if !StringSliceExists(slice, items[i]) {
- return false
- }
- }
-
- return true
-}
-
-// StringSliceExists --
-func StringSliceExists(slice []string, item string) bool {
- for i := 0; i < len(slice); i++ {
- if slice[i] == item {
- return true
- }
- }
-
- return false
-}
-
-// StringSliceUniqueAdd append the given item if not already present in the slice
-func StringSliceUniqueAdd(slice *[]string, item string) bool {
- if slice == nil {
- newSlice := make([]string, 0)
- slice = &newSlice
- }
- for _, i := range *slice {
- if i == item {
- return false
- }
- }
-
- *slice = append(*slice, item)
-
- return true
-}
-
-// StringSliceUniqueConcat append all the items of the "items" slice if they are not already present in the slice
-func StringSliceUniqueConcat(slice *[]string, items []string) bool {
- for _, item := range items {
- if !StringSliceUniqueAdd(slice, item) {
- return false
- }
- }
- return true
-}
-
-// EncodeXML --
-func EncodeXML(content interface{}) ([]byte, error) {
- w := &bytes.Buffer{}
- w.WriteString(xml.Header)
-
- e := xml.NewEncoder(w)
- e.Indent("", " ")
-
- err := e.Encode(content)
- if err != nil {
- return []byte{}, err
- }
-
- return w.Bytes(), nil
-}
-
-// CopyFile --
-func CopyFile(src, dst string) (int64, error) {
- sourceFileStat, err := os.Stat(src)
- if err != nil {
- return 0, err
- }
-
- if !sourceFileStat.Mode().IsRegular() {
- return 0, fmt.Errorf("%s is not a regular file", src)
- }
-
- source, err := os.Open(src)
- if err != nil {
- return 0, err
- }
- defer source.Close()
-
- err = os.MkdirAll(path.Dir(dst), 0777)
- if err != nil {
- return 0, err
- }
-
- destination, err := os.Create(dst)
- if err != nil {
- return 0, err
- }
- defer destination.Close()
- nBytes, err := io.Copy(destination, source)
- return nBytes, err
-}
-
-// WriteFileWithContent --
-func WriteFileWithContent(buildDir string, relativePath string, content []byte) error {
- filePath := path.Join(buildDir, relativePath)
- fileDir := path.Dir(filePath)
- // Create dir if not present
- err := os.MkdirAll(fileDir, 0777)
- if err != nil {
- return errors.Wrap(err, "could not create dir for file "+relativePath)
- }
- // Create file
- file, err := os.Create(filePath)
- if err != nil {
- return errors.Wrap(err, "could not create file "+relativePath)
- }
- defer file.Close()
-
- _, err = file.Write(content)
- if err != nil {
- return errors.Wrap(err, "could not write to file "+relativePath)
- }
- return nil
-}
-
-// WriteFileWithBytesMarshallerContent --
-func WriteFileWithBytesMarshallerContent(buildDir string, relativePath string, content BytesMarshaller) error {
- data, err := content.MarshalBytes()
- if err != nil {
- return err
- }
-
- return WriteFileWithContent(buildDir, relativePath, data)
-}
-
-// FindAllDistinctStringSubmatch --
-func FindAllDistinctStringSubmatch(data string, regexps ...*regexp.Regexp) []string {
- submatchs := strset.New()
-
- for _, reg := range regexps {
- hits := reg.FindAllStringSubmatch(data, -1)
- for _, hit := range hits {
- if len(hit) > 1 {
- for _, match := range hit[1:] {
- submatchs.Add(match)
- }
- }
- }
- }
- return submatchs.List()
-}
-
-// FileExists --
-func FileExists(name string) (bool, error) {
- info, err := os.Stat(name)
- if os.IsNotExist(err) {
- return false, nil
- }
-
- return !info.IsDir(), err
-}
-
-// BytesMarshaller --
-type BytesMarshaller interface {
- MarshalBytes() ([]byte, error)
-}
-
-// SortedStringMapKeys --
-func SortedStringMapKeys(m map[string]string) []string {
- res := make([]string, len(m))
- i := 0
- for k := range m {
- res[i] = k
- i++
- }
- sort.Strings(res)
- return res
-}
diff --git a/pkg/util/watch/watch.go b/pkg/util/watch/watch.go
deleted file mode 100644
index 21b08ba..0000000
--- a/pkg/util/watch/watch.go
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package watch
-
-import (
- "context"
- "fmt"
-
- v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
- "github.com/apache/camel-k/pkg/util/kubernetes"
- "github.com/apache/camel-k/pkg/util/kubernetes/customclient"
- "github.com/apache/camel-k/pkg/util/log"
- corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/runtime"
- "k8s.io/apimachinery/pkg/util/json"
-)
-
-//
-// HandleIntegrationStateChanges watches a integration resource and invoke the given handler when its status changes.
-//
-// err := watch.HandleIntegrationStateChanges(ctx, integration, func(i *v1.Integration) bool {
-// if i.Status.Phase == v1.IntegrationPhaseRunning {
-// return false
-// }
-//
-// return true
-// })
-//
-// This function blocks until the handler function returns true or either the events channel or the context is closed.
-//
-func HandleIntegrationStateChanges(ctx context.Context, integration *v1.Integration,
- handler func(integration *v1.Integration) bool) (*v1.IntegrationPhase, error) {
- dynamicClient, err := customclient.GetDefaultDynamicClientFor("integrations", integration.Namespace)
- if err != nil {
- return nil, err
- }
-
- watcher, err := dynamicClient.Watch(metav1.ListOptions{
- FieldSelector: "metadata.name=" + integration.Name,
- ResourceVersion: integration.ObjectMeta.ResourceVersion,
- })
- if err != nil {
- return nil, err
- }
-
- defer watcher.Stop()
- events := watcher.ResultChan()
-
- var lastObservedState *v1.IntegrationPhase
-
- var handlerWrapper = func(it *v1.Integration) bool {
- if lastObservedState == nil || *lastObservedState != it.Status.Phase {
- lastObservedState = &it.Status.Phase
- if !handler(it) {
- return false
- }
- }
- return true
- }
-
- // Check completion before starting the watch
- if !handlerWrapper(integration) {
- return lastObservedState, nil
- }
-
- for {
- select {
- case <-ctx.Done():
- return lastObservedState, nil
- case e, ok := <-events:
- if !ok {
- return lastObservedState, nil
- }
-
- if e.Object != nil {
- if runtimeUnstructured, ok := e.Object.(runtime.Unstructured); ok {
- jsondata, err := kubernetes.ToJSON(runtimeUnstructured)
- if err != nil {
- return nil, err
- }
- copy := integration.DeepCopy()
- err = json.Unmarshal(jsondata, copy)
- if err != nil {
- log.Error(err, "Unexpected error detected when watching resource")
- return lastObservedState, nil
- }
-
- if !handlerWrapper(copy) {
- return lastObservedState, nil
- }
- }
- }
- }
- }
-}
-
-//
-// HandleIntegrationEvents watches all events related to the given integration.
-//
-// watch.HandleIntegrationEvents(o.Context, integration, func(event *corev1.Event) bool {
-// println(event.Message)
-// return true
-// })
-//
-// This function blocks until the handler function returns true or either the events channel or the context is closed.
-//
-func HandleIntegrationEvents(ctx context.Context, integration *v1.Integration,
- handler func(event *corev1.Event) bool) error {
- dynamicClient, err := customclient.GetDynamicClientFor("", "v1", "events", integration.Namespace)
- if err != nil {
- return err
- }
- watcher, err := dynamicClient.Watch(metav1.ListOptions{
- FieldSelector: fmt.Sprintf("involvedObject.kind=Integration,"+
- "involvedObject.apiVersion=%s,"+
- "involvedObject.name=%s",
- v1.SchemeGroupVersion.String(), integration.Name),
- })
- if err != nil {
- return err
- }
-
- defer watcher.Stop()
- events := watcher.ResultChan()
-
- for {
- select {
- case <-ctx.Done():
- return nil
- case e, ok := <-events:
- if !ok {
- return nil
- }
-
- if e.Object != nil {
- if runtimeUnstructured, ok := e.Object.(runtime.Unstructured); ok {
- jsondata, err := kubernetes.ToJSON(runtimeUnstructured)
- if err != nil {
- return err
- }
- evt := corev1.Event{}
- err = json.Unmarshal(jsondata, &evt)
- if err != nil {
- log.Error(err, "Unexpected error detected when watching resource")
- return nil
- }
-
- if evt.CreationTimestamp.UnixNano() >= integration.CreationTimestamp.UnixNano() {
- if !handler(&evt) {
- return nil
- }
- }
- }
- }
- }
- }
-}
-
-//
-// HandlePlatformStateChanges watches a platform resource and invoke the given handler when its status changes.
-//
-// err := watch.HandlePlatformStateChanges(ctx, platform, func(i *v1.IntegrationPlatform) bool {
-// if i.Status.Phase == v1.IntegrationPlatformPhaseReady {
-// return false
-// }
-//
-// return true
-// })
-//
-// This function blocks until the handler function returns true or either the events channel or the context is closed.
-//
-func HandlePlatformStateChanges(ctx context.Context, platform *v1.IntegrationPlatform, handler func(platform *v1.IntegrationPlatform) bool) error {
- dynamicClient, err := customclient.GetDefaultDynamicClientFor("integrationplatforms", platform.Namespace)
- if err != nil {
- return err
- }
- watcher, err := dynamicClient.Watch(metav1.ListOptions{
- FieldSelector: "metadata.name=" + platform.Name,
- })
- if err != nil {
- return err
- }
-
- defer watcher.Stop()
- events := watcher.ResultChan()
-
- var lastObservedState *v1.IntegrationPlatformPhase
-
- var handlerWrapper = func(pl *v1.IntegrationPlatform) bool {
- if lastObservedState == nil || *lastObservedState != pl.Status.Phase {
- lastObservedState = &pl.Status.Phase
- if !handler(pl) {
- return false
- }
- }
- return true
- }
-
- // Check completion before starting the watch
- if !handlerWrapper(platform) {
- return nil
- }
-
- for {
- select {
- case <-ctx.Done():
- return nil
- case e, ok := <-events:
- if !ok {
- return nil
- }
-
- if e.Object != nil {
- if runtimeUnstructured, ok := e.Object.(runtime.Unstructured); ok {
- jsondata, err := kubernetes.ToJSON(runtimeUnstructured)
- if err != nil {
- return err
- }
- copy := platform.DeepCopy()
- err = json.Unmarshal(jsondata, copy)
- if err != nil {
- log.Error(err, "Unexpected error detected when watching resource")
- return nil
- }
-
- if !handlerWrapper(copy) {
- return nil
- }
- }
- }
- }
- }
-}
-
-//
-// HandleIntegrationPlatformEvents watches all events related to the given integration platform.
-//
-// watch.HandleIntegrationPlatformEvents(o.Context, platform, func(event *corev1.Event) bool {
-// println(event.Message)
-// return true
-// })
-//
-// This function blocks until the handler function returns true or either the events channel or the context is closed.
-//
-func HandleIntegrationPlatformEvents(ctx context.Context, p *v1.IntegrationPlatform,
- handler func(event *corev1.Event) bool) error {
- dynamicClient, err := customclient.GetDynamicClientFor("", "v1", "events", p.Namespace)
- if err != nil {
- return err
- }
- watcher, err := dynamicClient.Watch(metav1.ListOptions{
- FieldSelector: fmt.Sprintf("involvedObject.kind=IntegrationPlatform,"+
- "involvedObject.apiVersion=%s,"+
- "involvedObject.name=%s",
- v1.SchemeGroupVersion.String(), p.Name),
- })
- if err != nil {
- return err
- }
-
- defer watcher.Stop()
- events := watcher.ResultChan()
-
- for {
- select {
- case <-ctx.Done():
- return nil
- case e, ok := <-events:
- if !ok {
- return nil
- }
-
- if e.Object != nil {
- if runtimeUnstructured, ok := e.Object.(runtime.Unstructured); ok {
- jsondata, err := kubernetes.ToJSON(runtimeUnstructured)
- if err != nil {
- return err
- }
- evt := corev1.Event{}
- err = json.Unmarshal(jsondata, &evt)
- if err != nil {
- log.Error(err, "Unexpected error detected when watching resource")
- return nil
- }
-
- if evt.CreationTimestamp.UnixNano() >= p.CreationTimestamp.UnixNano() {
- if !handler(&evt) {
- return nil
- }
- }
- }
- }
- }
- }
-}
diff --git a/pkg/util/zip/zip.go b/pkg/util/zip/zip.go
deleted file mode 100644
index a5f59de..0000000
--- a/pkg/util/zip/zip.go
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You 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.
-*/
-
-package zip
-
-import (
- "archive/zip"
- "io"
- "os"
- "path/filepath"
- "strings"
-)
-
-func Directory(pathToZip, destinationPath string) error {
- destinationFile, err := os.Create(destinationPath)
- if err != nil {
- return err
- }
- myZip := zip.NewWriter(destinationFile)
- err = filepath.Walk(pathToZip, func(filePath string, info os.FileInfo, err error) error {
- if info.IsDir() {
- return nil
- }
- if err != nil {
- return err
- }
- relPath := strings.TrimPrefix(filePath, pathToZip)
- zipFile, err := myZip.Create(relPath)
- if err != nil {
- return err
- }
- fsFile, err := os.Open(filePath)
- if err != nil {
- return err
- }
- _, err = io.Copy(zipFile, fsFile)
- if err != nil {
- return err
- }
- return nil
- })
- if err != nil {
- return err
- }
- err = myZip.Close()
- if err != nil {
- return err
- }
- return nil
-}