codehaus


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[GitHub] lburgazzoli closed pull request #313: chore(knative): improvements for creating Knative CamelSources


lburgazzoli closed pull request #313: chore(knative): improvements for creating Knative CamelSources
URL: https://github.com/apache/camel-k/pull/313
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/cmd/camel-k/main.go b/cmd/camel-k/main.go
index e5d71f3e..67da2fe2 100644
--- a/cmd/camel-k/main.go
+++ b/cmd/camel-k/main.go
@@ -28,7 +28,7 @@ import (
 	"github.com/operator-framework/operator-sdk/pkg/util/k8sutil"
 	sdkVersion "github.com/operator-framework/operator-sdk/version"
 
-	_ "github.com/apache/camel-k/pkg/util/knative"
+	_ "github.com/apache/camel-k/pkg/apis/camel/v1alpha1/knative"
 	_ "github.com/apache/camel-k/pkg/util/openshift"
 
 	"github.com/sirupsen/logrus"
diff --git a/cmd/kamel/main.go b/cmd/kamel/main.go
index e711d0de..18822eab 100644
--- a/cmd/kamel/main.go
+++ b/cmd/kamel/main.go
@@ -26,7 +26,7 @@ import (
 
 	"github.com/apache/camel-k/pkg/client/cmd"
 
-	_ "github.com/apache/camel-k/pkg/util/knative"
+	_ "github.com/apache/camel-k/pkg/apis/camel/v1alpha1/knative"
 	_ "github.com/apache/camel-k/pkg/util/openshift"
 	_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
 )
diff --git a/pkg/util/knative/register.go b/pkg/apis/camel/v1alpha1/knative/register.go
similarity index 100%
rename from pkg/util/knative/register.go
rename to pkg/apis/camel/v1alpha1/knative/register.go
diff --git a/pkg/util/knative/types.go b/pkg/apis/camel/v1alpha1/knative/types.go
similarity index 100%
rename from pkg/util/knative/types.go
rename to pkg/apis/camel/v1alpha1/knative/types.go
diff --git a/pkg/apis/camel/v1alpha1/knative/types_support.go b/pkg/apis/camel/v1alpha1/knative/types_support.go
new file mode 100644
index 00000000..25f9ac9e
--- /dev/null
+++ b/pkg/apis/camel/v1alpha1/knative/types_support.go
@@ -0,0 +1,94 @@
+/*
+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 (
+	"encoding/json"
+	"net/url"
+	"strconv"
+)
+
+// BuildCamelServiceDefinition creates a CamelServiceDefinition from a given URL
+func BuildCamelServiceDefinition(name string, serviceType CamelServiceType, rawurl string) (*CamelServiceDefinition, error) {
+	serviceURL, err := url.Parse(rawurl)
+	if err != nil {
+		return nil, err
+	}
+	protocol := CamelProtocol(serviceURL.Scheme)
+	definition := CamelServiceDefinition{
+		Name:        name,
+		Host:        serviceURL.Host,
+		Port:        defaultCamelProtocolPort(protocol),
+		ServiceType: serviceType,
+		Protocol:    protocol,
+		Metadata:    make(map[string]string),
+	}
+	portStr := serviceURL.Port()
+	if portStr != "" {
+		port, err := strconv.Atoi(portStr)
+		if err != nil {
+			return nil, err
+		}
+		definition.Port = port
+	}
+	path := serviceURL.Path
+	if path != "" {
+		definition.Metadata[CamelMetaServicePath] = path
+	} else {
+		definition.Metadata[CamelMetaServicePath] = "/"
+	}
+	return &definition, nil
+}
+
+func defaultCamelProtocolPort(prot CamelProtocol) int {
+	switch prot {
+	case CamelProtocolHTTP:
+		return 80
+	case CamelProtocolHTTPS:
+		return 443
+	default:
+		return -1
+	}
+}
+
+// Serialize serializes a CamelEnvironment
+func (env *CamelEnvironment) Serialize() (string, error) {
+	res, err := json.Marshal(env)
+	if err != nil {
+		return "", err
+	}
+	return string(res), nil
+}
+
+// Deserialize deserializes a camel environment into this struct
+func (env *CamelEnvironment) Deserialize(str string) error {
+	if err := json.Unmarshal([]byte(str), env); err != nil {
+		return err
+	}
+	return nil
+}
+
+// ContainsService tells if the environment contains a service with the given name and type
+func (env *CamelEnvironment) ContainsService(name string, serviceType CamelServiceType) bool {
+	for _, svc := range env.Services {
+		if svc.Name == name && svc.ServiceType == serviceType {
+			return true
+		}
+	}
+	return false
+}
diff --git a/pkg/apis/camel/v1alpha1/types.go b/pkg/apis/camel/v1alpha1/types.go
index ef4dcc05..9951e3fe 100644
--- a/pkg/apis/camel/v1alpha1/types.go
+++ b/pkg/apis/camel/v1alpha1/types.go
@@ -363,6 +363,9 @@ type Flow struct {
 	Steps []Step `json:"steps"`
 }
 
+// Flows are collections of Flow
+type Flows []Flow
+
 // Step --
 type Step struct {
 	Kind string `json:"kind"`
diff --git a/pkg/apis/camel/v1alpha1/types_support.go b/pkg/apis/camel/v1alpha1/types_support.go
index 21df6053..95a842f9 100644
--- a/pkg/apis/camel/v1alpha1/types_support.go
+++ b/pkg/apis/camel/v1alpha1/types_support.go
@@ -19,6 +19,7 @@ package v1alpha1
 
 import (
 	"fmt"
+	"gopkg.in/yaml.v2"
 	"strings"
 
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -128,3 +129,12 @@ func TraitProfileByName(name string) TraitProfile {
 	}
 	return ""
 }
+
+// Serialize serializes a Flow
+func (flows Flows) Serialize() (string, error) {
+	res, err := yaml.Marshal(flows)
+	if err != nil {
+		return "", err
+	}
+	return string(res), nil
+}
diff --git a/pkg/trait/knative.go b/pkg/trait/knative.go
index ae2e30da..977d6add 100644
--- a/pkg/trait/knative.go
+++ b/pkg/trait/knative.go
@@ -18,7 +18,6 @@ limitations under the License.
 package trait
 
 import (
-	"encoding/json"
 	"fmt"
 
 	"github.com/apache/camel-k/pkg/util/envvar"
@@ -31,6 +30,7 @@ import (
 
 	"github.com/apache/camel-k/pkg/apis/camel/v1alpha1"
 
+	knativeapi "github.com/apache/camel-k/pkg/apis/camel/v1alpha1/knative"
 	"github.com/apache/camel-k/pkg/metadata"
 	knativeutil "github.com/apache/camel-k/pkg/util/knative"
 	eventing "github.com/knative/eventing/pkg/apis/eventing/v1alpha1"
@@ -45,12 +45,13 @@ const (
 )
 
 type knativeTrait struct {
-	BaseTrait `property:",squash"`
-	Sources   string `property:"sources"`
-	Sinks     string `property:"sinks"`
-	MinScale  *int   `property:"minScale"`
-	MaxScale  *int   `property:"maxScale"`
-	Auto      *bool  `property:"auto"`
+	BaseTrait     `property:",squash"`
+	Configuration string `property:"configuration"`
+	Sources       string `property:"sources"`
+	Sinks         string `property:"sinks"`
+	MinScale      *int   `property:"minScale"`
+	MaxScale      *int   `property:"maxScale"`
+	Auto          *bool  `property:"auto"`
 }
 
 func newKnativeTrait() *knativeTrait {
@@ -288,27 +289,29 @@ func (t *knativeTrait) getConfigurationSerialized(e *Environment) (string, error
 	if err != nil {
 		return "", errors.Wrap(err, "unable fetch environment configuration")
 	}
+	return env.Serialize()
+}
 
-	res, err := json.Marshal(env)
-	if err != nil {
-		return "", errors.Wrap(err, "unable to serialize Knative configuration")
+func (t *knativeTrait) getConfiguration(e *Environment) (knativeapi.CamelEnvironment, error) {
+	env := knativeapi.NewCamelEnvironment()
+	if t.Configuration != "" {
+		env.Deserialize(t.Configuration)
 	}
-	return string(res), nil
-}
 
-func (t *knativeTrait) getConfiguration(e *Environment) (knativeutil.CamelEnvironment, error) {
-	env := knativeutil.NewCamelEnvironment()
 	// Sources
 	sourceChannels := t.getConfiguredSourceChannels()
 	for _, ch := range sourceChannels {
-		svc := knativeutil.CamelServiceDefinition{
+		if env.ContainsService(ch, knativeapi.CamelServiceTypeChannel) {
+			continue
+		}
+		svc := knativeapi.CamelServiceDefinition{
 			Name:        ch,
 			Host:        "0.0.0.0",
 			Port:        8080,
-			Protocol:    knativeutil.CamelProtocolHTTP,
-			ServiceType: knativeutil.CamelServiceTypeChannel,
+			Protocol:    knativeapi.CamelProtocolHTTP,
+			ServiceType: knativeapi.CamelServiceTypeChannel,
 			Metadata: map[string]string{
-				knativeutil.CamelMetaServicePath: "/",
+				knativeapi.CamelMetaServicePath: "/",
 			},
 		}
 		env.Services = append(env.Services, svc)
@@ -316,6 +319,9 @@ func (t *knativeTrait) getConfiguration(e *Environment) (knativeutil.CamelEnviro
 	// Sinks
 	sinkChannels := t.getConfiguredSinkChannels()
 	for _, ch := range sinkChannels {
+		if env.ContainsService(ch, knativeapi.CamelServiceTypeChannel) {
+			continue
+		}
 		channel, err := t.retrieveChannel(e.Integration.Namespace, ch)
 		if err != nil {
 			return env, err
@@ -324,27 +330,27 @@ func (t *knativeTrait) getConfiguration(e *Environment) (knativeutil.CamelEnviro
 		if hostname == "" {
 			return env, errors.New("cannot find address of channel " + ch)
 		}
-		svc := knativeutil.CamelServiceDefinition{
+		svc := knativeapi.CamelServiceDefinition{
 			Name:        ch,
 			Host:        hostname,
 			Port:        80,
-			Protocol:    knativeutil.CamelProtocolHTTP,
-			ServiceType: knativeutil.CamelServiceTypeChannel,
+			Protocol:    knativeapi.CamelProtocolHTTP,
+			ServiceType: knativeapi.CamelServiceTypeChannel,
 			Metadata: map[string]string{
-				knativeutil.CamelMetaServicePath: "/",
+				knativeapi.CamelMetaServicePath: "/",
 			},
 		}
 		env.Services = append(env.Services, svc)
 	}
 	// Adding default endpoint
-	defSvc := knativeutil.CamelServiceDefinition{
+	defSvc := knativeapi.CamelServiceDefinition{
 		Name:        "default",
 		Host:        "0.0.0.0",
 		Port:        8080,
-		Protocol:    knativeutil.CamelProtocolHTTP,
-		ServiceType: knativeutil.CamelServiceTypeEndpoint,
+		Protocol:    knativeapi.CamelProtocolHTTP,
+		ServiceType: knativeapi.CamelServiceTypeEndpoint,
 		Metadata: map[string]string{
-			knativeutil.CamelMetaServicePath: "/",
+			knativeapi.CamelMetaServicePath: "/",
 		},
 	}
 	env.Services = append(env.Services, defSvc)
diff --git a/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeComponent.java b/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeComponent.java
index 0767fdaa..264f644a 100644
--- a/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeComponent.java
+++ b/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeComponent.java
@@ -30,6 +30,8 @@
     private final KnativeConfiguration configuration;
     private String environmentPath;
 
+    private boolean jsonSerializationEnabled;
+
     public KnativeComponent() {
         this(null);
     }
@@ -116,4 +118,12 @@ private KnativeConfiguration getKnativeConfiguration() throws Exception {
 
         return conf;
     }
+
+    public boolean isJsonSerializationEnabled() {
+        return jsonSerializationEnabled;
+    }
+
+    public void setJsonSerializationEnabled(boolean jsonSerializationEnabled) {
+        this.jsonSerializationEnabled = jsonSerializationEnabled;
+    }
 }
diff --git a/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeConversionProcessor.java b/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeConversionProcessor.java
new file mode 100644
index 00000000..6ff5830a
--- /dev/null
+++ b/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeConversionProcessor.java
@@ -0,0 +1,28 @@
+package org.apache.camel.component.knative;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+
+/**
+ * Converts objects prior to serializing them to external endpoints or channels
+ */
+public class KnativeConversionProcessor implements Processor {
+
+    private boolean enabled;
+
+    public KnativeConversionProcessor(boolean enabled) {
+        this.enabled = enabled;
+    }
+
+    @Override
+    public void process(Exchange exchange) throws Exception {
+        if (enabled) {
+            Object body = exchange.getIn().getBody();
+            if (body != null) {
+                byte[] newBody = Knative.MAPPER.writeValueAsBytes(body);
+                exchange.getIn().setBody(newBody);
+                exchange.getIn().setHeader("CE-ContentType", "application/json");
+            }
+        }
+    }
+}
diff --git a/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeEndpoint.java b/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeEndpoint.java
index 10f264c2..89c7f3bb 100644
--- a/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeEndpoint.java
+++ b/runtime/camel-knative/src/main/java/org/apache/camel/component/knative/KnativeEndpoint.java
@@ -16,13 +16,6 @@
  */
 package org.apache.camel.component.knative;
 
-import java.io.InputStream;
-import java.time.ZoneId;
-import java.time.ZonedDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.HashMap;
-import java.util.Map;
-
 import org.apache.camel.CamelContext;
 import org.apache.camel.Consumer;
 import org.apache.camel.DelegateEndpoint;
@@ -44,6 +37,13 @@
 import org.apache.camel.util.URISupport;
 import org.apache.commons.lang3.StringUtils;
 
+import java.io.InputStream;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.HashMap;
+import java.util.Map;
+
 import static org.apache.camel.util.ObjectHelper.ifNotEmpty;
 
 
@@ -100,6 +100,11 @@ protected void doStop() throws Exception {
         super.doStop();
     }
 
+    @Override
+    public KnativeComponent getComponent() {
+        return (KnativeComponent) super.getComponent();
+    }
+
     @Override
     public Producer createProducer() throws Exception {
         return new KnativeProducer(
@@ -121,6 +126,7 @@ public Producer createProducer() throws Exception {
                 // Always remove host so it's always computed from the URL and not inherited from the exchange
                 headers.remove("Host");
             },
+            new KnativeConversionProcessor(getComponent().isJsonSerializationEnabled()),
             endpoint.createProducer()
         );
     }


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@xxxxxxxxxxxxxxxx


With regards,
Apache Git Services