nicolaferraro closed pull request #107: Refactor build, deploy and run workflow
URL: https://github.com/apache/camel-k/pull/107
 
 
   

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/Gopkg.lock b/Gopkg.lock
index 2efc6d9..4c8e50f 100644
--- a/Gopkg.lock
+++ b/Gopkg.lock
@@ -742,7 +742,6 @@
     "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured",
     "k8s.io/apimachinery/pkg/runtime",
     "k8s.io/apimachinery/pkg/runtime/schema",
-    "k8s.io/apimachinery/pkg/runtime/serializer",
     "k8s.io/apimachinery/pkg/runtime/serializer/json",
     "k8s.io/apimachinery/pkg/runtime/serializer/versioning",
     "k8s.io/apimachinery/pkg/util/yaml",
diff --git a/deploy/platform-integration-context-core.yaml 
b/deploy/platform-integration-context-core.yaml
index 836d195..d0d3289 100644
--- a/deploy/platform-integration-context-core.yaml
+++ b/deploy/platform-integration-context-core.yaml
@@ -1,9 +1,12 @@
 apiVersion: camel.apache.org/v1alpha1
 kind: IntegrationContext
 metadata:
-  name: root.integrationcontexts.camel.apache.org
+  name: core
   labels:
     app: "camel-k"
     camel.apache.org/context.created.by.kind: Operator
     camel.apache.org/context.created.by.name: core
-    camel.apache.org/context.type: platform
\ No newline at end of file
+    camel.apache.org/context.type: platform
+spec:
+  dependencies:
+    - camel:core
\ No newline at end of file
diff --git a/deploy/platform-integration-context-groovy.yaml 
b/deploy/platform-integration-context-groovy.yaml
index 5c5cbf4..cabe24a 100644
--- a/deploy/platform-integration-context-groovy.yaml
+++ b/deploy/platform-integration-context-groovy.yaml
@@ -1,7 +1,7 @@
 apiVersion: camel.apache.org/v1alpha1
 kind: IntegrationContext
 metadata:
-  name: groovy.integrationcontexts.camel.apache.org
+  name: groovy
   labels:
     app: "camel-k"
     camel.apache.org/context.created.by.kind: Operator
@@ -9,4 +9,5 @@ metadata:
     camel.apache.org/context.type: platform
 spec:
   dependencies:
+    - camel:core
     - camel:groovy
\ No newline at end of file
diff --git a/deploy/resources.go b/deploy/resources.go
index e9525d6..7a9888f 100644
--- a/deploy/resources.go
+++ b/deploy/resources.go
@@ -2441,19 +2441,22 @@ status:
 apiVersion: camel.apache.org/v1alpha1
 kind: IntegrationContext
 metadata:
-  name: root.integrationcontexts.camel.apache.org
+  name: core
   labels:
     app: "camel-k"
     camel.apache.org/context.created.by.kind: Operator
     camel.apache.org/context.created.by.name: core
     camel.apache.org/context.type: platform
+spec:
+  dependencies:
+    - camel:core
 `
        Resources["platform-integration-context-groovy.yaml"] =
                `
 apiVersion: camel.apache.org/v1alpha1
 kind: IntegrationContext
 metadata:
-  name: groovy.integrationcontexts.camel.apache.org
+  name: groovy
   labels:
     app: "camel-k"
     camel.apache.org/context.created.by.kind: Operator
@@ -2461,6 +2464,7 @@ metadata:
     camel.apache.org/context.type: platform
 spec:
   dependencies:
+    - camel:core
     - camel:groovy
 `
        Resources["user-cluster-role.yaml"] =
diff --git a/pkg/apis/camel/v1alpha1/types.go b/pkg/apis/camel/v1alpha1/types.go
index 3a91be6..80ebe59 100644
--- a/pkg/apis/camel/v1alpha1/types.go
+++ b/pkg/apis/camel/v1alpha1/types.go
@@ -130,9 +130,10 @@ type IntegrationContextSpec struct {
 
 // IntegrationContextStatus --
 type IntegrationContextStatus struct {
-       Phase  IntegrationContextPhase `json:"phase,omitempty"`
-       Image  string                  `json:"image,omitempty"`
-       Digest string                  `json:"digest,omitempty"`
+       Phase     IntegrationContextPhase `json:"phase,omitempty"`
+       Image     string                  `json:"image,omitempty"`
+       Digest    string                  `json:"digest,omitempty"`
+       Classpath []string                `json:"classpath,omitempty"`
 }
 
 // IntegrationContextPhase --
diff --git a/pkg/apis/camel/v1alpha1/zz_generated.deepcopy.go 
b/pkg/apis/camel/v1alpha1/zz_generated.deepcopy.go
index 9feb415..0784edc 100644
--- a/pkg/apis/camel/v1alpha1/zz_generated.deepcopy.go
+++ b/pkg/apis/camel/v1alpha1/zz_generated.deepcopy.go
@@ -75,7 +75,7 @@ func (in *IntegrationContext) DeepCopyInto(out 
*IntegrationContext) {
        out.TypeMeta = in.TypeMeta
        in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
        in.Spec.DeepCopyInto(&out.Spec)
-       out.Status = in.Status
+       in.Status.DeepCopyInto(&out.Status)
        return
 }
 
@@ -159,6 +159,11 @@ func (in *IntegrationContextSpec) DeepCopy() 
*IntegrationContextSpec {
 // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, 
writing into out. in must be non-nil.
 func (in *IntegrationContextStatus) DeepCopyInto(out 
*IntegrationContextStatus) {
        *out = *in
+       if in.Classpath != nil {
+               in, out := &in.Classpath, &out.Classpath
+               *out = make([]string, len(*in))
+               copy(*out, *in)
+       }
        return
 }
 
diff --git a/pkg/build/build_manager.go b/pkg/build/build_manager.go
index 325e995..50d1187 100644
--- a/pkg/build/build_manager.go
+++ b/pkg/build/build_manager.go
@@ -57,7 +57,7 @@ func (m *Manager) Start(source Request) {
        resChannel := m.builder.Build(source)
        go func() {
                res := <-resChannel
-               m.builds.Store(res.Source.Identifier, &res)
+               m.builds.Store(res.Request.Identifier, &res)
        }()
 }
 
@@ -69,7 +69,7 @@ func noBuildInfo() Result {
 
 func initialBuildInfo(source *Request) Result {
        return Result{
-               Source: source,
-               Status: StatusStarted,
+               Request: source,
+               Status:  StatusStarted,
        }
 }
diff --git a/pkg/build/build_types.go b/pkg/build/build_types.go
index da1ffed..dc7c787 100644
--- a/pkg/build/build_types.go
+++ b/pkg/build/build_types.go
@@ -39,10 +39,17 @@ type Source struct {
 
 // Result represents the result of a build
 type Result struct {
-       Source *Request
-       Status Status
-       Image  string
-       Error  error
+       Request   *Request
+       Status    Status
+       Image     string
+       Error     error
+       Classpath []ClasspathEntry
+}
+
+// ClasspathEntry --
+type ClasspathEntry struct {
+       ID       string `json:"id" yaml:"id"`
+       Location string `json:"location,omitempty" yaml:"location,omitempty"`
 }
 
 // Builder is supertype of all builders
diff --git a/pkg/build/local/local_builder.go b/pkg/build/local/local_builder.go
index c341274..232360b 100644
--- a/pkg/build/local/local_builder.go
+++ b/pkg/build/local/local_builder.go
@@ -51,8 +51,8 @@ type localBuilder struct {
 }
 
 type buildOperation struct {
-       source build.Request
-       output chan build.Result
+       request build.Request
+       output  chan build.Result
 }
 
 // NewLocalBuilder create a new builder
@@ -65,11 +65,11 @@ func NewLocalBuilder(ctx context.Context, namespace string) 
build.Builder {
        return &builder
 }
 
-func (b *localBuilder) Build(source build.Request) <-chan build.Result {
+func (b *localBuilder) Build(request build.Request) <-chan build.Result {
        res := make(chan build.Result, 1)
        op := buildOperation{
-               source: source,
-               output: res,
+               request: request,
+               output:  res,
        }
        b.buffer <- op
        return res
@@ -84,54 +84,57 @@ func (b *localBuilder) buildCycle(ctx context.Context) {
                case op := <-b.buffer:
                        now := time.Now()
                        logrus.Info("Starting new build")
-                       image, err := b.execute(op.source)
+                       res := b.execute(&op.request)
                        elapsed := time.Now().Sub(now)
-                       if err != nil {
-                               logrus.Error("Error during build (total time ", 
elapsed.Seconds(), " seconds): ", err)
-                       } else {
-                               logrus.Info("Build completed in ", 
elapsed.Seconds(), " seconds")
-                       }
 
-                       if err != nil {
-                               op.output <- build.Result{
-                                       Source: &op.source,
-                                       Status: build.StatusError,
-                                       Error:  err,
-                               }
+                       if res.Error != nil {
+                               logrus.Error("Error during build (total time ", 
elapsed.Seconds(), " seconds): ", res.Error)
                        } else {
-                               op.output <- build.Result{
-                                       Source: &op.source,
-                                       Status: build.StatusCompleted,
-                                       Image:  image,
-                               }
+                               logrus.Info("Process completed in ", 
elapsed.Seconds(), " seconds")
                        }
 
+                       op.output <- res
                }
        }
 }
 
-func (b *localBuilder) execute(source build.Request) (string, error) {
-       integration, err := generateIntegration(source)
+func (b *localBuilder) execute(request *build.Request) build.Result {
+       project, err := generateProject(request)
        if err != nil {
-               return "", err
+               return build.Result{
+                       Error:  err,
+                       Status: build.StatusError,
+               }
        }
-       tarFileName, err := maven.Build(integration)
+
+       res, err := maven.Process(project)
        if err != nil {
-               return "", err
+               return build.Result{
+                       Error:  err,
+                       Status: build.StatusError,
+               }
        }
 
-       logrus.Info("Created tar file ", tarFileName)
+       logrus.Info("Created tar file ", res.TarFilePath)
 
-       image, err := b.publish(tarFileName, source)
+       image, err := b.publish(res.TarFilePath, request)
        if err != nil {
-               return "", errors.Wrap(err, "could not publish docker image")
+               return build.Result{
+                       Error:  errors.Wrap(err, "could not publish docker 
image"),
+                       Status: build.StatusError,
+               }
        }
 
-       return image, nil
+       return build.Result{
+               Request:   request,
+               Image:     image,
+               Error:     nil,
+               Status:    build.StatusCompleted,
+               Classpath: res.Classpath,
+       }
 }
 
-func (b *localBuilder) publish(tarFile string, source build.Request) (string, 
error) {
-
+func (b *localBuilder) publish(tarFile string, source *build.Request) (string, 
error) {
        bc := buildv1.BuildConfig{
                TypeMeta: metav1.TypeMeta{
                        APIVersion: buildv1.SchemeGroupVersion.String(),
@@ -150,7 +153,7 @@ func (b *localBuilder) publish(tarFile string, source 
build.Request) (string, er
                                        SourceStrategy: 
&buildv1.SourceBuildStrategy{
                                                From: v1.ObjectReference{
                                                        Kind: "DockerImage",
-                                                       Name: 
"fabric8/s2i-java:2.1",
+                                                       Name: 
"fabric8/s2i-java:2.3",
                                                },
                                        },
                                },
@@ -254,44 +257,40 @@ func (b *localBuilder) publish(tarFile string, source 
build.Request) (string, er
        return is.Status.DockerImageRepository + ":" + 
source.Identifier.Qualifier, nil
 }
 
-func generateIntegration(source build.Request) (maven.Integration, error) {
-       integration := maven.Integration{
-               Project: maven.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",
-                       GroupID:           "org.apache.camel.k.integration",
-                       ArtifactID:        "camel-k-integration",
-                       Version:           version.Version,
-                       DependencyManagement: maven.DependencyManagement{
-                               Dependencies: maven.Dependencies{
-                                       Dependencies: []maven.Dependency{
-                                               {
-                                                       //TODO: camel version 
should be retrieved from an external source or provided as static version
-                                                       GroupID:    
"org.apache.camel",
-                                                       ArtifactID: "camel-bom",
-                                                       Version:    "2.22.1",
-                                                       Type:       "pom",
-                                                       Scope:      "import",
-                                               },
+func generateProject(source *build.Request) (maven.Project, error) {
+       project := maven.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",
+               GroupID:           "org.apache.camel.k.integration",
+               ArtifactID:        "camel-k-integration",
+               Version:           version.Version,
+               DependencyManagement: maven.DependencyManagement{
+                       Dependencies: maven.Dependencies{
+                               Dependencies: []maven.Dependency{
+                                       {
+                                               //TODO: camel version should be 
retrieved from an external request or provided as static version
+                                               GroupID:    "org.apache.camel",
+                                               ArtifactID: "camel-bom",
+                                               Version:    "2.22.1",
+                                               Type:       "pom",
+                                               Scope:      "import",
                                        },
                                },
                        },
-                       Dependencies: maven.Dependencies{
-                               Dependencies: make([]maven.Dependency, 0),
-                       },
                },
-               Resources: make(map[string]string),
-               Env:       make(map[string]string),
+               Dependencies: maven.Dependencies{
+                       Dependencies: make([]maven.Dependency, 0),
+               },
        }
 
        //
        // set-up dependencies
        //
 
-       deps := &integration.Project.Dependencies
+       deps := &project.Dependencies
        deps.AddGAV("org.apache.camel.k", "camel-k-runtime-jvm", 
version.Version)
 
        for _, d := range source.Dependencies {
@@ -309,9 +308,9 @@ func generateIntegration(source build.Request) 
(maven.Integration, error) {
 
                        deps.AddEncodedGAV(gav)
                } else {
-                       return maven.Integration{}, fmt.Errorf("unknown 
dependency type: %s", d)
+                       return maven.Project{}, fmt.Errorf("unknown dependency 
type: %s", d)
                }
        }
 
-       return integration, nil
+       return project, nil
 }
diff --git a/pkg/build/local/local_builder_test.go 
b/pkg/build/local/local_builder_test.go
index c5fd33d..ddb928e 100644
--- a/pkg/build/local/local_builder_test.go
+++ b/pkg/build/local/local_builder_test.go
@@ -25,7 +25,7 @@ import (
 )
 
 func TestProjectGeneration(t *testing.T) {
-       source := build.Request{
+       request := build.Request{
                Identifier: build.Identifier{
                        Name:      "my-integration",
                        Qualifier: "",
@@ -43,21 +43,22 @@ func TestProjectGeneration(t *testing.T) {
                },
        }
 
-       prj, err := generateIntegration(source)
+       prj, err := generateProject(&request)
+
        assert.Nil(t, err)
        assert.NotNil(t, prj)
-       assert.Equal(t, len(prj.Project.Dependencies.Dependencies), 5)
-       assert.Equal(t, prj.Project.Dependencies.Dependencies[0].ArtifactID, 
"camel-k-runtime-jvm")
-       assert.Equal(t, prj.Project.Dependencies.Dependencies[1].ArtifactID, 
"camel-mail")
-       assert.Equal(t, prj.Project.Dependencies.Dependencies[2].ArtifactID, 
"camel-netty4")
-       assert.Equal(t, prj.Project.Dependencies.Dependencies[3].ArtifactID, 
"camel-servicenow")
-       assert.Equal(t, prj.Project.Dependencies.Dependencies[3].Version, 
"2.21.1")
-       assert.Equal(t, prj.Project.Dependencies.Dependencies[4].ArtifactID, 
"camel-salesforce")
-       assert.Equal(t, prj.Project.Dependencies.Dependencies[4].Version, "")
+       assert.Equal(t, len(prj.Dependencies.Dependencies), 5)
+       assert.Equal(t, prj.Dependencies.Dependencies[0].ArtifactID, 
"camel-k-runtime-jvm")
+       assert.Equal(t, prj.Dependencies.Dependencies[1].ArtifactID, 
"camel-mail")
+       assert.Equal(t, prj.Dependencies.Dependencies[2].ArtifactID, 
"camel-netty4")
+       assert.Equal(t, prj.Dependencies.Dependencies[3].ArtifactID, 
"camel-servicenow")
+       assert.Equal(t, prj.Dependencies.Dependencies[3].Version, "2.21.1")
+       assert.Equal(t, prj.Dependencies.Dependencies[4].ArtifactID, 
"camel-salesforce")
+       assert.Equal(t, prj.Dependencies.Dependencies[4].Version, "")
 }
 
 func TestProjectGenerationWithFailure(t *testing.T) {
-       source := build.Request{
+       request := build.Request{
                Identifier: build.Identifier{
                        Name:      "my-integration",
                        Qualifier: "",
@@ -75,6 +76,7 @@ func TestProjectGenerationWithFailure(t *testing.T) {
                },
        }
 
-       _, err := generateIntegration(source)
+       _, err := generateProject(&request)
+
        assert.NotNil(t, err)
 }
diff --git a/pkg/discover/dependencies_test.go 
b/pkg/discover/dependencies_test.go
index ca5fff2..8e48cb1 100644
--- a/pkg/discover/dependencies_test.go
+++ b/pkg/discover/dependencies_test.go
@@ -18,14 +18,15 @@ limitations under the License.
 package discover
 
 import (
+       "testing"
+
        "github.com/apache/camel-k/pkg/apis/camel/v1alpha1"
        "github.com/stretchr/testify/assert"
-       "testing"
 )
 
 func TestDependenciesJavaSource(t *testing.T) {
        code := v1alpha1.SourceSpec{
-               Name: "Source.java",
+               Name:     "Request.java",
                Language: v1alpha1.LanguageJavaSource,
                Content: `
                        from("telegram:bots/cippa").to("log:stash");
@@ -40,7 +41,7 @@ func TestDependenciesJavaSource(t *testing.T) {
 
 func TestDependenciesJavaClass(t *testing.T) {
        code := v1alpha1.SourceSpec{
-               Name: "Source.class",
+               Name:     "Request.class",
                Language: v1alpha1.LanguageJavaClass,
                Content: `
                        from("telegram:bots/cippa").to("log:stash");
@@ -54,7 +55,7 @@ func TestDependenciesJavaClass(t *testing.T) {
 
 func TestDependenciesJavaScript(t *testing.T) {
        code := v1alpha1.SourceSpec{
-               Name: "source.js",
+               Name:     "source.js",
                Language: v1alpha1.LanguageJavaScript,
                Content: `
                        from('telegram:bots/cippa').to("log:stash");
@@ -70,7 +71,7 @@ func TestDependenciesJavaScript(t *testing.T) {
 
 func TestDependenciesGroovy(t *testing.T) {
        code := v1alpha1.SourceSpec{
-               Name: "source.groovy",
+               Name:     "source.groovy",
                Language: v1alpha1.LanguageGroovy,
                Content: `
                        from('telegram:bots/cippa').to("log:stash");
@@ -82,4 +83,4 @@ func TestDependenciesGroovy(t *testing.T) {
        dependencies := Dependencies(code)
        // assert all dependencies are found and sorted (removing duplicates)
        assert.Equal(t, []string{"camel:amqp", "camel:core", "camel:telegram"}, 
dependencies)
-}
\ No newline at end of file
+}
diff --git a/pkg/discover/languages_test.go b/pkg/discover/languages_test.go
index 919de9d..bbe0c45 100644
--- a/pkg/discover/languages_test.go
+++ b/pkg/discover/languages_test.go
@@ -18,14 +18,15 @@ limitations under the License.
 package discover
 
 import (
+       "testing"
+
        "github.com/apache/camel-k/pkg/apis/camel/v1alpha1"
        "github.com/stretchr/testify/assert"
-       "testing"
 )
 
 func TestLanguageJavaSource(t *testing.T) {
        code := v1alpha1.SourceSpec{
-               Name: "Source.java",
+               Name: "Request.java",
        }
        language := Language(code)
        assert.Equal(t, v1alpha1.LanguageJavaSource, language)
@@ -33,7 +34,7 @@ func TestLanguageJavaSource(t *testing.T) {
 
 func TestLanguageAlreadySet(t *testing.T) {
        code := v1alpha1.SourceSpec{
-               Name:     "Source.java",
+               Name:     "Request.java",
                Language: v1alpha1.LanguageJavaScript,
        }
        language := Language(code)
diff --git a/pkg/stub/action/context/build.go b/pkg/stub/action/context/build.go
index e8d26e4..9d5d3b1 100644
--- a/pkg/stub/action/context/build.go
+++ b/pkg/stub/action/context/build.go
@@ -73,6 +73,12 @@ func (action *integrationContextBuildAction) Handle(context 
*v1alpha1.Integratio
                target := context.DeepCopy()
                target.Status.Image = buildResult.Image
                target.Status.Phase = v1alpha1.IntegrationContextPhaseReady
+
+               target.Status.Classpath = make([]string, 
len(buildResult.Classpath))
+               for i, entry := range buildResult.Classpath {
+                       target.Status.Classpath[i] = entry.ID
+               }
+
                if err := sdk.Update(target); err != nil {
                        return err
                }
diff --git a/pkg/stub/action/integration/deploy.go 
b/pkg/stub/action/integration/deploy.go
index 8d873ea..b3bce77 100644
--- a/pkg/stub/action/integration/deploy.go
+++ b/pkg/stub/action/integration/deploy.go
@@ -142,6 +142,8 @@ func getDeploymentFor(ctx *v1alpha1.IntegrationContext, 
integration *v1alpha1.In
 
        // set env vars needed by the runtime
        environment["JAVA_MAIN_CLASS"] = "org.apache.camel.k.jvm.Application"
+
+       // camel-k runtime
        environment["CAMEL_K_ROUTES_URI"] = "file:/etc/camel/conf/" + sourceName
        environment["CAMEL_K_ROUTES_LANGUAGE"] = 
string(integration.Spec.Source.Language)
        environment["CAMEL_K_CONF"] = "/etc/camel/conf/application.properties"
diff --git a/pkg/util/maven/maven.go b/pkg/util/maven/maven.go
index c54ebd2..66a0cd1 100644
--- a/pkg/util/maven/maven.go
+++ b/pkg/util/maven/maven.go
@@ -21,6 +21,7 @@ import (
        "archive/tar"
        "bytes"
        "encoding/xml"
+       "fmt"
        "io"
        "io/ioutil"
        "os"
@@ -29,6 +30,11 @@ import (
        "regexp"
        "strings"
 
+       "github.com/apache/camel-k/version"
+
+       "github.com/apache/camel-k/pkg/build"
+       "gopkg.in/yaml.v1"
+
        "github.com/pkg/errors"
        "github.com/sirupsen/logrus"
 )
@@ -38,47 +44,64 @@ const (
        artifactDirPrefix = "maven-bin-"
 )
 
-// Build takes a project description and returns a binary tar with the built 
artifacts
-func Build(integration Integration) (string, error) {
+// BuildResult --
+type BuildResult struct {
+       TarFilePath string
+       Classpath   []build.ClasspathEntry
+}
+
+// Process takes a project description and returns a binary tar with the built 
artifacts
+func Process(project Project) (BuildResult, error) {
+       res := BuildResult{}
        buildDir, err := ioutil.TempDir("", buildDirPrefix)
        if err != nil {
-               return "", errors.Wrap(err, "could not create temporary dir for 
maven source files")
+               return res, errors.Wrap(err, "could not create temporary dir 
for maven source files")
        }
+
        defer os.RemoveAll(buildDir)
 
-       err = createMavenStructure(buildDir, integration)
+       err = createMavenStructure(buildDir, project)
        if err != nil {
-               return "", errors.Wrap(err, "could not write maven source 
files")
+               return res, errors.Wrap(err, "could not write maven source 
files")
        }
-       err = runMavenBuild(buildDir)
+       err = runMavenBuild(buildDir, &res)
        if err != nil {
-               return "", err
+               return res, err
        }
-       tarfile, err := createTar(buildDir, integration)
+
+       res.TarFilePath, err = createTar(project, &res)
        if err != nil {
-               return "", err
+               return res, err
        }
-       return tarfile, nil
+
+       return res, nil
 }
 
-func runMavenBuild(buildDir string) error {
-       mavenBuild := exec.Command("mvn", mavenExtraOptions(), "clean", 
"install", "-DskipTests")
-       mavenBuild.Dir = buildDir
-       mavenBuild.Stdout = os.Stdout
-       mavenBuild.Stderr = os.Stderr
-       logrus.Info("Starting maven build: mvn " + mavenExtraOptions() + " 
clean install -DskipTests")
-       err := mavenBuild.Run()
-       if err != nil {
-               return errors.Wrap(err, "failure while executing maven build")
+func runMavenBuild(buildDir string, result *BuildResult) error {
+       goal := 
fmt.Sprintf("org.apache.camel.k:camel-k-runtime-dependency-lister:%s:generate-dependency-list",
 version.Version)
+       cmd := exec.Command("mvn", mavenExtraOptions(), goal)
+       cmd.Dir = buildDir
+       cmd.Stdout = os.Stdout
+       cmd.Stderr = os.Stderr
+
+       logrus.Infof("determine classpath: %v", cmd.Args)
+       if err := cmd.Run(); err != nil {
+               return errors.Wrap(err, "failure while determining classpath")
        }
 
-       mavenDep := exec.Command("mvn", mavenExtraOptions(), 
"dependency:copy-dependencies")
-       mavenDep.Dir = buildDir
-       logrus.Info("Copying maven dependencies: mvn " + mavenExtraOptions() + 
" dependency:copy-dependencies")
-       err = mavenDep.Run()
+       dependencies := path.Join(buildDir, "target", "dependencies.yaml")
+       content, err := ioutil.ReadFile(dependencies)
        if err != nil {
-               return errors.Wrap(err, "failure while extracting maven 
dependencies")
+               return err
+       }
+
+       cp := make(map[string][]build.ClasspathEntry)
+       if err := yaml.Unmarshal(content, &cp); err != nil {
+               return err
        }
+
+       result.Classpath = cp["dependencies"]
+
        logrus.Info("Maven build completed successfully")
        return nil
 }
@@ -90,13 +113,13 @@ func mavenExtraOptions() string {
        return "-Dcamel.noop=true"
 }
 
-func createTar(buildDir string, integration Integration) (string, error) {
+func createTar(project Project, result *BuildResult) (string, error) {
        artifactDir, err := ioutil.TempDir("", artifactDirPrefix)
        if err != nil {
                return "", errors.Wrap(err, "could not create temporary dir for 
maven artifacts")
        }
 
-       tarFileName := path.Join(artifactDir, 
integration.Project.ArtifactID+".tar")
+       tarFileName := path.Join(artifactDir, project.ArtifactID+".tar")
        tarFile, err := os.Create(tarFileName)
        if err != nil {
                return "", errors.Wrap(err, "cannot create tar file 
"+tarFileName)
@@ -104,45 +127,36 @@ func createTar(buildDir string, integration Integration) 
(string, error) {
        defer tarFile.Close()
 
        writer := tar.NewWriter(tarFile)
-       err = appendToTar(path.Join(buildDir, "target", 
integration.Project.ArtifactID+"-"+integration.Project.Version+".jar"), "", 
writer)
-       if err != nil {
-               return "", err
-       }
+       defer writer.Close()
 
-       // Environment variables
-       if integration.Env != nil {
-               err = writeFile(buildDir, "run-env.sh", 
envFileContent(integration.Env))
+       cp := ""
+       for _, entry := range result.Classpath {
+               gav, err := ParseGAV(entry.ID)
                if err != nil {
-                       return "", err
+                       return "", nil
                }
-               err = appendToTar(path.Join(buildDir, "run-env.sh"), "", writer)
+
+               tarPath := path.Join("dependencies/", gav.GroupID)
+               fileName, err := appendFileToTar(entry.Location, tarPath, 
writer)
                if err != nil {
                        return "", err
                }
+
+               cp += fileName + "\n"
        }
 
-       dependenciesDir := path.Join(buildDir, "target", "dependency")
-       dependencies, err := ioutil.ReadDir(dependenciesDir)
+       err = appendDataToTar([]byte(cp), "classpath", writer)
        if err != nil {
                return "", err
        }
 
-       for _, dep := range dependencies {
-               err = appendToTar(path.Join(dependenciesDir, dep.Name()), "", 
writer)
-               if err != nil {
-                       return "", err
-               }
-       }
-
-       writer.Close()
-
        return tarFileName, nil
 }
 
-func appendToTar(filePath string, tarPath string, writer *tar.Writer) error {
+func appendFileToTar(filePath string, tarPath string, writer *tar.Writer) 
(string, error) {
        info, err := os.Stat(filePath)
        if err != nil {
-               return err
+               return "", err
        }
        _, fileName := path.Split(filePath)
        if tarPath != "" {
@@ -158,31 +172,39 @@ func appendToTar(filePath string, tarPath string, writer 
*tar.Writer) error {
 
        file, err := os.Open(filePath)
        if err != nil {
-               return err
+               return "", err
        }
        defer file.Close()
 
        _, err = io.Copy(writer, file)
        if err != nil {
-               return errors.Wrap(err, "cannot add file to the tar archive")
+               return "", errors.Wrap(err, "cannot add file to the tar 
archive")
        }
-       return nil
+
+       return fileName, nil
 }
 
-func createMavenStructure(buildDir string, project Integration) error {
-       pom, err := GeneratePomFileContent(project.Project)
-       if err != nil {
-               return err
-       }
-       err = writeFile(buildDir, "pom.xml", pom)
+func appendDataToTar(data []byte, tarPath string, writer *tar.Writer) error {
+       writer.WriteHeader(&tar.Header{
+               Name: tarPath,
+               Size: int64(len(data)),
+               Mode: 0644,
+       })
+
+       _, err := writer.Write(data)
        if err != nil {
-               return err
+               return errors.Wrap(err, "cannot add data to the tar archive")
        }
-       err = writeFiles(path.Join(buildDir, "src", "main", "java"), 
project.JavaSources)
+       return nil
+}
+
+func createMavenStructure(buildDir string, project Project) error {
+       pom, err := GeneratePomFileContent(project)
        if err != nil {
                return err
        }
-       err = writeFiles(path.Join(buildDir, "src", "main", "resources"), 
project.Resources)
+
+       err = writeFile(buildDir, "pom.xml", pom)
        if err != nil {
                return err
        }
@@ -190,19 +212,6 @@ func createMavenStructure(buildDir string, project 
Integration) error {
        return nil
 }
 
-func writeFiles(buildDir string, files map[string]string) error {
-       if files == nil {
-               return nil
-       }
-       for fileName, fileContent := range files {
-               err := writeFile(buildDir, fileName, fileContent)
-               if err != nil {
-                       return err
-               }
-       }
-       return nil
-}
-
 func writeFile(buildDir string, relativePath string, content string) error {
        filePath := path.Join(buildDir, relativePath)
        fileDir := path.Dir(filePath)
@@ -225,17 +234,6 @@ func writeFile(buildDir string, relativePath string, 
content string) error {
        return nil
 }
 
-func envFileContent(env map[string]string) string {
-       if env == nil {
-               return ""
-       }
-       content := ""
-       for k, v := range env {
-               content = content + "export " + k + "=" + v + "\n"
-       }
-       return content
-}
-
 // GeneratePomFileContent generate a pom.xml file from the given project 
definition
 func GeneratePomFileContent(project Project) (string, error) {
        w := &bytes.Buffer{}
diff --git a/pkg/util/maven/types.go b/pkg/util/maven/maven_project.go
similarity index 60%
rename from pkg/util/maven/types.go
rename to pkg/util/maven/maven_project.go
index db4b897..95cf928 100644
--- a/pkg/util/maven/types.go
+++ b/pkg/util/maven/maven_project.go
@@ -21,14 +21,6 @@ import (
        "encoding/xml"
 )
 
-// Integration --
-type Integration struct {
-       Project     Project
-       JavaSources map[string]string
-       Resources   map[string]string
-       Env         map[string]string // TODO: should we deprecate it ? env are 
set on deployment
-}
-
 // Project represent a maven project
 type Project struct {
        XMLName              xml.Name
@@ -41,6 +33,8 @@ type Project struct {
        Version              string               `xml:"version"`
        DependencyManagement DependencyManagement `xml:"dependencyManagement"`
        Dependencies         Dependencies         `xml:"dependencies"`
+       Repositories         Repositories         `xml:"repositories"`
+       PluginRepositories   PluginRepositories   `xml:"pluginRepositories"`
 }
 
 // DependencyManagement represent maven's dependency management block
@@ -91,3 +85,86 @@ func NewDependency(groupID string, artifactID string, 
version string) Dependency
                Classifier: "",
        }
 }
+
+// Repositories --
+type Repositories struct {
+       Repositories []Repository `xml:"repository"`
+}
+
+// PluginRepositories --
+type PluginRepositories struct {
+       Repositories []Repository `xml:"pluginRepository"`
+}
+
+// Repository --
+type Repository struct {
+       ID        string    `xml:"id"`
+       Name      string    `xml:"name"`
+       URL       string    `xml:"url"`
+       Snapshots Snapshots `xml:"snapshots"`
+       Releases  Releases  `xml:"releases"`
+}
+
+// Snapshots --
+type Snapshots struct {
+       Enabled      bool   `xml:"enabled"`
+       UpdatePolicy string `xml:"updatePolicy"`
+}
+
+// Releases --
+type Releases struct {
+       Enabled      bool   `xml:"enabled"`
+       UpdatePolicy string `xml:"updatePolicy"`
+}
+
+// Build --
+type Build struct {
+       Plugins Plugins `xml:"plugins,omitempty"`
+}
+
+// Plugin --
+type Plugin struct {
+       GroupID    string     `xml:"groupId"`
+       ArtifactID string     `xml:"artifactId"`
+       Version    string     `xml:"version,omitempty"`
+       Executions Executions `xml:"executions"`
+}
+
+// Plugins --
+type Plugins struct {
+       Plugins []Plugin `xml:"plugin"`
+}
+
+// Execution --
+type Execution struct {
+       ID    string `xml:"id"`
+       Phase string `xml:"phase"`
+       Goals Goals  `xml:"goals,omitempty"`
+}
+
+// Executions --
+type Executions struct {
+       Executions []Execution `xml:"execution"`
+}
+
+// Goals --
+type Goals struct {
+       Goals []string `xml:"goal"`
+}
+
+/*
+ <plugin>
+        <groupId>org.apache.camel.k</groupId>
+        <artifactId>camel-k-runtime-dependency-lister</artifactId>
+        <version>0.0.3-SNAPSHOT</version>
+        <executions>
+          <execution>
+            <id>generate-dependency-list</id>
+            <phase>initialize</phase>
+            <goals>
+              <goal>generate-dependency-list</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+*/
diff --git a/pkg/util/maven/maven_test.go b/pkg/util/maven/maven_test.go
index 05cff20..d21109c 100644
--- a/pkg/util/maven/maven_test.go
+++ b/pkg/util/maven/maven_test.go
@@ -48,6 +48,36 @@ const expectedPom = `<?xml version="1.0" encoding="UTF-8"?>
       <version>1.0.0</version>
     </dependency>
   </dependencies>
+  <repositories>
+    <repository>
+      <id>central</id>
+      <name></name>
+      <url>https://repo.maven.apache.org/maven2</url>
+      <snapshots>
+        <enabled>false</enabled>
+        <updatePolicy>never</updatePolicy>
+      </snapshots>
+      <releases>
+        <enabled>true</enabled>
+        <updatePolicy>never</updatePolicy>
+      </releases>
+    </repository>
+  </repositories>
+  <pluginRepositories>
+    <pluginRepository>
+      <id>central</id>
+      <name></name>
+      <url>https://repo.maven.apache.org/maven2</url>
+      <snapshots>
+        <enabled>false</enabled>
+        <updatePolicy>never</updatePolicy>
+      </snapshots>
+      <releases>
+        <enabled>true</enabled>
+        <updatePolicy>never</updatePolicy>
+      </releases>
+    </pluginRepository>
+  </pluginRepositories>
 </project>`
 
 func TestPomGeneration(t *testing.T) {
@@ -82,6 +112,38 @@ func TestPomGeneration(t *testing.T) {
                                },
                        },
                },
+               Repositories: Repositories{
+                       Repositories: []Repository{
+                               {
+                                       ID:  "central",
+                                       URL: 
"https://repo.maven.apache.org/maven2";,
+                                       Snapshots: Snapshots{
+                                               Enabled:      false,
+                                               UpdatePolicy: "never",
+                                       },
+                                       Releases: Releases{
+                                               Enabled:      true,
+                                               UpdatePolicy: "never",
+                                       },
+                               },
+                       },
+               },
+               PluginRepositories: PluginRepositories{
+                       Repositories: []Repository{
+                               {
+                                       ID:  "central",
+                                       URL: 
"https://repo.maven.apache.org/maven2";,
+                                       Snapshots: Snapshots{
+                                               Enabled:      false,
+                                               UpdatePolicy: "never",
+                                       },
+                                       Releases: Releases{
+                                               Enabled:      true,
+                                               UpdatePolicy: "never",
+                                       },
+                               },
+                       },
+               },
        }
 
        pom, err := GeneratePomFileContent(project)
diff --git a/runtime/dependency-lister/.gitignore 
b/runtime/dependency-lister/.gitignore
new file mode 100644
index 0000000..ed92983
--- /dev/null
+++ b/runtime/dependency-lister/.gitignore
@@ -0,0 +1,10 @@
+target
+
+*.iml
+
+.idea
+.project
+.metadata
+.settings
+.factorypath
+.classpath
diff --git a/runtime/dependency-lister/pom.xml 
b/runtime/dependency-lister/pom.xml
new file mode 100644
index 0000000..0bd8e91
--- /dev/null
+++ b/runtime/dependency-lister/pom.xml
@@ -0,0 +1,99 @@
+<?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";>
+  <parent>
+    <groupId>org.apache.camel.k</groupId>
+    <artifactId>camel-k-runtime-parent</artifactId>
+    <version>0.0.3-SNAPSHOT</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <packaging>maven-plugin</packaging>
+
+  <artifactId>camel-k-runtime-dependency-lister</artifactId>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.maven</groupId>
+      <artifactId>maven-core</artifactId>
+      <version>3.5.2</version>
+      <exclusions>
+        <exclusion>
+          <groupId>*</groupId>
+          <artifactId>*</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.maven.plugin-tools</groupId>
+      <artifactId>maven-plugin-annotations</artifactId>
+      <version>3.5.2</version>
+      <exclusions>
+        <exclusion>
+          <groupId>org.codehaus.plexus</groupId>
+          <artifactId>plexus-utils</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.maven.shared</groupId>
+      <artifactId>maven-common-artifact-filters</artifactId>
+      <version>3.0.1</version>
+      <exclusions>
+        <exclusion>
+          <groupId>org.apache.maven</groupId>
+          <artifactId>maven-repository-metadata</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>org.codehaus.plexus</groupId>
+          <artifactId>plexus-utils</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.maven</groupId>
+      <artifactId>maven-plugin-api</artifactId>
+      <version>3.5.2</version>
+      <exclusions>
+        <exclusion>
+          <groupId>*</groupId>
+          <artifactId>*</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>org.yaml</groupId>
+      <artifactId>snakeyaml</artifactId>
+      <version>${snakeyaml.version}</version>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-plugin-plugin</artifactId>
+        <version>3.5.2</version>
+        <configuration>
+          <mojoDependencies/>
+        </configuration>
+        <executions>
+          <execution>
+            <id>default-descriptor</id>
+            <phase>process-classes</phase>
+            <goals>
+              <goal>descriptor</goal>
+            </goals>
+          </execution>
+          <execution>
+            <id>help-goal</id>
+            <goals>
+              <goal>helpmojo</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
diff --git 
a/runtime/dependency-lister/src/main/java/org/apache/camel/k/tooling/maven/dependency/DependencyListerMojo.java
 
b/runtime/dependency-lister/src/main/java/org/apache/camel/k/tooling/maven/dependency/DependencyListerMojo.java
new file mode 100644
index 0000000..780c9e8
--- /dev/null
+++ 
b/runtime/dependency-lister/src/main/java/org/apache/camel/k/tooling/maven/dependency/DependencyListerMojo.java
@@ -0,0 +1,101 @@
+/**
+ * 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 org.apache.camel.k.tooling.maven.dependency;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.artifact.DefaultArtifact;
+import org.apache.maven.artifact.factory.ArtifactFactory;
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.plugins.annotations.Component;
+import org.apache.maven.plugins.annotations.LifecyclePhase;
+import org.apache.maven.plugins.annotations.Mojo;
+import org.apache.maven.plugins.annotations.Parameter;
+import org.apache.maven.plugins.annotations.ResolutionScope;
+import org.apache.maven.project.MavenProject;
+import org.apache.maven.shared.utils.StringUtils;
+import org.yaml.snakeyaml.DumperOptions;
+import org.yaml.snakeyaml.Yaml;
+
+@Mojo(
+    name = "generate-dependency-list",
+    defaultPhase = LifecyclePhase.PREPARE_PACKAGE,
+    requiresProject = true,
+    threadSafe = true,
+    requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME,
+    requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME)
+@SuppressWarnings({ "PMD.GodClass", "PMD.TooManyFields", "PMD.TooManyMethods" 
})
+public class DependencyListerMojo extends AbstractMojo {
+
+    @Component
+    private ArtifactFactory artifactFactory;
+
+    @Parameter(readonly = true, defaultValue = "${project}")
+    private MavenProject project;
+
+    @Parameter(readonly = true, defaultValue = 
"${project.build.directory}/dependencies.yaml")
+    private String destination;
+
+    @Override
+    public void execute() throws MojoExecutionException, MojoFailureException {
+        List<Map<String, String>> deps = new ArrayList<>();
+
+        
project.getArtifacts().stream().filter(this::isCompileOrRuntime).forEach(artifact
 -> {
+                Map<String, String> dep = new HashMap<>();
+                dep.put("id", artifact.getId());
+
+                if (artifact.getFile() != null) {
+                    dep.put("location", artifact.getFile().getAbsolutePath());
+                }
+
+                deps.add(dep);
+            }
+        );
+
+        File dest = new File(destination);
+        if (!dest.getParentFile().exists()) {
+            dest.getParentFile().mkdirs();
+        }
+
+        try (Writer writer = new FileWriter(dest)) {
+
+            DumperOptions options = new DumperOptions();
+            options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
+
+            Yaml yaml = new Yaml(options);
+            yaml.dump(Collections.singletonMap("dependencies", deps), writer);
+        } catch (IOException e) {
+            throw new MojoExecutionException("Exception while generating 
dependencies list", e);
+        }
+    }
+
+    private boolean isCompileOrRuntime(Artifact artifact) {
+        return StringUtils.equals(artifact.getScope(), 
DefaultArtifact.SCOPE_COMPILE)
+            || StringUtils.equals(artifact.getScope(), 
DefaultArtifact.SCOPE_RUNTIME);
+    }
+}
diff --git a/runtime/pom.xml b/runtime/pom.xml
index 74cd8aa..0948ca3 100644
--- a/runtime/pom.xml
+++ b/runtime/pom.xml
@@ -56,6 +56,7 @@
     <modules>
         <module>jvm</module>
         <module>catalog-builder</module>
+        <module>dependency-lister</module>
     </modules>
 
 </project>
diff --git a/tmp/build/Dockerfile b/tmp/build/Dockerfile
index df1abde..cbd151d 100644
--- a/tmp/build/Dockerfile
+++ b/tmp/build/Dockerfile
@@ -1,4 +1,4 @@
-FROM fabric8/s2i-java:2.1
+FROM fabric8/s2i-java:2.3
 
 #RUN adduser -D camel-k-operator
 #USER camel-k-operator


 

----------------------------------------------------------------
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:
[email protected]


With regards,
Apache Git Services

Reply via email to