Esempio n. 1
0
  private static String getReadMeFileKey(String relativePath) {
    String answer = relativePath;

    if (Strings.isNullOrBlank(answer)) {
      return "<root>";
    }

    // remove leading path which can be either unix or windows style
    int pos = relativePath.indexOf('/');
    int pos2 = relativePath.indexOf('\\');
    if (pos > 0 && pos2 > 0) {
      pos = Math.max(pos, pos2);
    } else if (pos2 > 0) {
      pos = pos2;
    }
    if (pos > -1) {
      answer = relativePath.substring(pos);
    }

    // and remove any leading path separators
    answer = Files.stripLeadingSeparator(answer);

    if (Strings.isNullOrBlank(answer)) {
      answer = "<root>";
    }
    return answer;
  }
Esempio n. 2
0
 /**
  * Resolves a logical environment name for a project, such as <code>Testing</code> to the physical
  * projcect/team specific namespace value.
  *
  * <p>It tries to find a fabric8.yml file in this folder or a parent folder and loads it and tries
  * to use it to find the namespace for the given environment or uses environment variables to
  * resolve the environment name -> physical namespace
  *
  * @return the namespace
  */
 private static String findNamespaceForEnvironment(String environment, Map<String, String> map) {
   String namespace = null;
   if (!Strings.isNullOrBlank(environment)) {
     String basedir = System.getProperty("basedir", ".");
     File folder = new File(basedir);
     ProjectConfig projectConfig = ProjectConfigs.findFromFolder(folder);
     if (projectConfig != null) {
       LinkedHashMap<String, String> environments = projectConfig.getEnvironments();
       if (environments != null) {
         namespace = environments.get(environment);
       }
     }
     String key = environment.toLowerCase() + ".namespace";
     if (Strings.isNullOrBlank(namespace)) {
       // lets try find an environment variable or system property
       namespace = getStringProperty(key, map, null);
     }
     if (Strings.isNullOrBlank(namespace)) {
       throw new IllegalStateException(
           "A fabric8 environment '"
               + environment
               + "' has been specified, but no matching namespace was found in the fabric8.yml file or '"
               + key
               + "' system property");
     }
   }
   return namespace;
 }
Esempio n. 3
0
  private MQBrokerConfigDTO createDTO() {
    if (Strings.isNullOrBlank(username)) {
      username = ShellUtils.retrieveFabricUser(session);
    }
    if (Strings.isNullOrBlank(password)) {
      password = ShellUtils.retrieveFabricUserPassword(session);
    }

    MQBrokerConfigDTO dto = new MQBrokerConfigDTO();
    dto.setConfigUrl(config);
    dto.setData(data);
    if (ports != null && ports.length > 0) {
      for (String port : ports) {
        addConfig(port, dto.getPorts());
      }
    }
    dto.setGroup(group);
    dto.setJvmOpts(jvmOpts);
    dto.setBrokerName(name);
    dto.setProfile(profile);
    dto.setClientProfile(clientProfile);
    dto.setClientParentProfile(clientParentProfile);
    dto.setNetworks(networks);
    dto.setNetworksPassword(networksPassword);
    dto.setNetworksUserName(networksUserName);
    dto.setParentProfile(parentProfile);
    dto.setProperties(properties);
    dto.setVersion(version);
    dto.setMinimumInstances(minimumInstances);
    dto.setReplicas(replicas);
    if (kind != null) {
      dto.setKind(kind);
    }
    return dto;
  }
Esempio n. 4
0
 protected boolean overrideFromEnvVar(String name, boolean defaultValue) {
   String envVar = envVarPrefix + name;
   String value = null;
   try {
     value = System.getenv(envVar);
     LOG.debug("Checking env var: " + envVar);
     if (Strings.isNullOrBlank(value)) {
       // lets try the generic value for all entities
       value = System.getProperty(ENV_VAR_PREFIX + name);
     }
     if (Strings.isNotBlank(value)) {
       Boolean b = Boolean.parseBoolean(value);
       if (b != null) {
         return b.booleanValue();
       }
     }
   } catch (Exception e) {
     LOG.warn(
         "Failed to parse boolean value for env var "
             + envVar
             + " with value `"
             + value
             + "`. "
             + e,
         e);
   }
   return defaultValue;
 }
Esempio n. 5
0
  protected void createAndCheckoutBranch()
      throws MojoExecutionException, IOException, GitAPIException {
    if (Strings.isNullOrBlank(oldBranchName)) {
      // lets find the previous branch
      List<String> branches =
          new ArrayList<String>(RepositoryUtils.getBranches(git.getRepository()));
      int size = branches.size();
      if (size > 0) {
        String last = branches.get(size - 1);
        int idx = last.lastIndexOf('/');
        if (idx > 0) {
          oldBranchName = last.substring(idx + 1);
          getLog().info("Using previous branch: " + oldBranchName);
        }
      }
    }
    if (Strings.isNullOrBlank(oldBranchName)) {
      oldBranchName = "master";
      getLog().warn("Could not deduce the old branch so setting it to: " + oldBranchName);
    }
    checkoutBranch(git, oldBranchName);
    getLog().info("Creating branch " + branchName + " in " + getGitBuildPathDescription());

    createOrCheckoutBranch(git, branchName, remoteName);
    checkoutBranch(git, branchName);
  }
Esempio n. 6
0
 protected void configureBranch(String branch) {
   // lets update the merge config
   if (Strings.isNotBlank(branch) && hasRemoteRepo()) {
     StoredConfig config = git.getRepository().getConfig();
     if (Strings.isNullOrBlank(config.getString("branch", branch, "remote"))
         || Strings.isNullOrBlank(config.getString("branch", branch, "merge"))) {
       config.setString("branch", branch, "remote", remoteName);
       config.setString("branch", branch, "merge", "refs/heads/" + branch);
       try {
         config.save();
       } catch (IOException e) {
         getLog()
             .error(
                 "Failed to save the git configuration into "
                     + new File(buildDir, ".git")
                     + " with branch "
                     + branch
                     + " on remote repo: "
                     + gitUrl
                     + " due: "
                     + e.getMessage()
                     + ". This exception is ignored.",
                 e);
       }
     }
   }
 }
Esempio n. 7
0
  public static Configuration fromMap(Map<String, String> map) {
    Configuration configuration = new Configuration();
    try {
      configuration.masterUrl =
          getStringProperty(KUBERNETES_MASTER, map, FALLBACK_CONFIG.getMasterUrl());
      configuration.environment = getStringProperty(FABRIC8_ENVIRONMENT, map, null);
      configuration.environmentInitEnabled =
          getBooleanProperty(ENVIRONMENT_INIT_ENABLED, map, true);
      configuration.environmentConfigUrl = getKubernetesConfigurationUrl(map);
      configuration.environmentDependencies =
          Strings.splitAndTrimAsList(getStringProperty(ENVIRONMENT_DEPENDENCIES, map, ""), " ");

      configuration.namespaceLazyCreateEnabled =
          getBooleanProperty(
              NAMESPACE_LAZY_CREATE_ENABLED, map, DEFAULT_NAMESPACE_LAZY_CREATE_ENABLED);

      String existingNamespace = getStringProperty(NAMESPACE_TO_USE, map, null);
      String environmentNamespace = findNamespaceForEnvironment(configuration.environment, map);
      configuration.namespaceToUse = selectNamespace(environmentNamespace, existingNamespace);

      // We default to "cleanup=true" when generating namespace and "cleanup=false" when using
      // existing namespace.
      configuration.namespaceCleanupEnabled =
          getBooleanProperty(
              NAMESPACE_CLEANUP_ENABLED, map, Strings.isNullOrBlank(configuration.namespaceToUse));
      configuration.namespaceCleanupConfirmationEnabled =
          getBooleanProperty(NAMESPACE_CLEANUP_CONFIRM_ENABLED, map, false);
      configuration.namespaceCleanupTimeout =
          getLongProperty(NAMESPACE_CLEANUP_TIMEOUT, map, DEFAULT_NAMESPACE_CLEANUP_TIMEOUT);

      configuration.waitTimeout = getLongProperty(WAIT_TIMEOUT, map, DEFAULT_WAIT_TIMEOUT);
      configuration.waitPollInterval =
          getLongProperty(WAIT_POLL_INTERVAL, map, DEFAULT_WAIT_POLL_INTERVAL);
      configuration.waitForServiceList =
          Strings.splitAndTrimAsList(getStringProperty(WAIT_FOR_SERVICE_LIST, map, ""), " ");
      configuration.waitForServiceConnectionEnabled =
          getBooleanProperty(
              WAIT_FOR_SERVICE_CONNECTION_ENABLED,
              map,
              DEFAULT_WAIT_FOR_SERVICE_CONNECTION_ENABLED);
      configuration.waitForServiceConnectionTimeout =
          getLongProperty(
              WAIT_FOR_SERVICE_CONNECTION_TIMEOUT, map, DEFAULT_NAMESPACE_CLEANUP_TIMEOUT);

      configuration.ansiLoggerEnabled = getBooleanProperty(ANSI_LOGGER_ENABLED, map, true);
      configuration.kubernetesDomain = getStringProperty(KUBERNETES_DOMAIN, map, "vagrant.f8");
      configuration.gofabric8Enabled = getBooleanProperty(GOFABRIC8_ENABLED, map, false);

      configuration.properties = map;
    } catch (Throwable t) {
      if (t instanceof RuntimeException) {
        throw (RuntimeException) t;
      } else {
        throw new RuntimeException(t);
      }
    }
    return configuration;
  }
Esempio n. 8
0
 /**
  * Returns true if the remote git url is defined or the local git repo has a remote url defined
  */
 protected boolean hasRemoteRepo() {
   if (Strings.isNotBlank(gitUrl)) {
     return true;
   }
   Repository repository = git.getRepository();
   StoredConfig config = repository.getConfig();
   String url = config.getString("remote", remoteName, "url");
   if (Strings.isNotBlank(url)) {
     return true;
   }
   return false;
 }
Esempio n. 9
0
  protected void doPull() throws MojoExecutionException {
    // CredentialsProvider cp = getCredentials();
    CredentialsProvider cp = null;
    try {
      Repository repository = git.getRepository();
      StoredConfig config = repository.getConfig();
      String url = config.getString("remote", "origin", "url");
      if (Strings.isNullOrBlank(url)) {
        getLog()
            .info(
                "No remote repository defined for the git repository at "
                    + getGitBuildPathDescription()
                    + " so not doing a pull");
        return;
      }
      String branch = repository.getBranch();
      String mergeUrl = config.getString("branch", branch, "merge");
      if (Strings.isNullOrBlank(mergeUrl)) {
        getLog()
            .info(
                "No merge spec for branch."
                    + branch
                    + ".merge in the git repository at "
                    + getGitBuildPathDescription()
                    + " so not doing a pull");
        return;
      }
      getLog()
          .info(
              "Performing a pull in git repository "
                  + getGitBuildPathDescription()
                  + " on remote URL: "
                  + url);

      git.pull().setCredentialsProvider(cp).setRebase(true).call();
    } catch (Throwable e) {
      String credText = "";
      if (cp instanceof UsernamePasswordCredentialsProvider) {}
      String message =
          "Failed to pull from the remote git repo with credentials "
              + cp
              + " due: "
              + e.getMessage()
              + ". This exception is ignored.";
      getLog().error(message, e);
      throw new MojoExecutionException(message, e);
    }
  }
Esempio n. 10
0
 public static String getFabric8ConsoleLink() {
   String answer = System.getenv("FABRIC8_CONSOLE");
   if (Strings.isNullOrBlank(answer)) {
     answer = DEFAULT_FABRIC8_CONSOLE;
   }
   return answer;
 }
 /** If a slug is not supplied then lets generate it from the project name */
 protected String validateSlug(String slug, String name) {
   if (Strings.isNotBlank(slug)) {
     return slug;
   } else {
     return getUsername() + "-" + name;
   }
 }
Esempio n. 12
0
 public void filter(ClientRequestContext requestContext) throws IOException {
   MultivaluedMap<String, Object> headers = requestContext.getHeaders();
   String authenticationHeader = getAuthenticationHeader();
   if (Strings.isNotBlank(authenticationHeader)) {
     headers.add("Authorization", authenticationHeader);
   }
 }
Esempio n. 13
0
  public static final String toAlias(
      String serviceName,
      String serviceProtocol,
      String servicePort,
      String servicePath,
      Boolean endpoint,
      Boolean external,
      String suffix) {
    StringBuilder sb = new StringBuilder();

    if (external) {
      sb.append("external");
    } else {
      sb.append("internal");
    }

    sb.append("-");

    if (endpoint) {
      sb.append("endpoint");
    } else {
      sb.append("service");
    }

    sb.append("-").append(serviceName);

    if (Strings.isNotBlank(serviceProtocol)) {
      sb.append("-").append(serviceProtocol);
    } else {
      sb.append("-").append("tcp");
    }

    if (Strings.isNotBlank(servicePort)) {
      sb.append("-").append(serviceProtocol);
    } else {
      sb.append("-").append("single");
    }

    if (Strings.isNotBlank(servicePath)) {
      sb.append("-").append(servicePath);
    } else {
      sb.append("-").append("root");
    }

    sb.append("-").append(suffix);
    return sb.toString();
  }
Esempio n. 14
0
 private String getAuthenticationHeader() {
   String token = getAuthToken();
   if (Strings.isNotBlank(token)) {
     return "Bearer " + token;
   } else {
     return null;
   }
 }
Esempio n. 15
0
 public static String or(String... candidates) {
   for (String candidate : candidates) {
     if (Strings.isNotBlank(candidate)) {
       return candidate;
     }
   }
   return null;
 }
Esempio n. 16
0
 private static ServicePort toNamedServicePort(String serviceId, ServicePort servicePort) {
   String portName = servicePort.getName();
   String protocol = servicePort.getProtocol();
   Integer nodePort = servicePort.getNodePort();
   IntOrString targetPort = servicePort.getTargetPort();
   String name =
       !Strings.isNullOrBlank(portName) ? portName : serviceId + "-" + targetPort.toString();
   int port = KubernetesHelper.intOrStringToInteger(targetPort, "service: " + name);
   return new ServicePort(name, nodePort, port, protocol, targetPort);
 }
 @Override
 public ConditionOutcome getMatchOutcome(
     ConditionContext context, AnnotatedTypeMetadata metadata) {
   String masterUrl = Utils.getSystemPropertyOrEnvVar(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY);
   if (!Strings.isNullOrBlank(masterUrl)) {
     return ConditionOutcome.match();
   }
   return ConditionOutcome.noMatch(
       "Url to kubernetes master, not found in environment variables or system properties.");
 }
Esempio n. 18
0
 protected PipelineDTO getPipelineForValue(UIContext context, String value) {
   if (Strings.isNotBlank(value)) {
     Iterable<PipelineDTO> pipelines = getPipelines(context, false);
     for (PipelineDTO pipelineDTO : pipelines) {
       if (pipelineDTO.getValue().equals(value) || pipelineDTO.toString().equals(value)) {
         return pipelineDTO;
       }
     }
   }
   return null;
 }
  public void addController(ReplicationController controller) {
    String id = getId(controller);
    if (Strings.isNotBlank(id)) {
      controllers.put(id, controller);

      // now lets find all the pods that are active for this
      List<Pod> pods = snapshot.podsForReplicationController(controller);
      for (Pod pod : pods) {
        addPod(pod);
      }
    }
  }
 /**
  * Returns the webhook URL for the given module.
  *
  * <p>The module webhook might not use the correct public host name so lets convert it.
  */
 public String getPublicWebhookUrl(ModuleDTO module) {
   if (module != null) {
     String webhooksUrl = module.getWebhooksUrl();
     if (Strings.isNotBlank(webhooksUrl)) {
       int idx = webhooksUrl.indexOf("/api/v");
       if (idx > 0) {
         return URLUtils.pathJoin(getAddress(), webhooksUrl.substring(idx));
       }
     }
     return webhooksUrl;
   }
   return null;
 }
Esempio n. 21
0
  @SuppressWarnings("unchecked")
  protected void uploadAppZip(boolean newUserAdded) throws Exception {
    File file = getZipFile();
    if (!file.exists()) {
      getLog()
          .error(
              "No App Zip file at "
                  + file.getAbsolutePath()
                  + ". Did you execute the fabric8:zip goal?");
      return;
    }
    if (!file.isFile()) {
      getLog()
          .error(
              "Invalid App Zip file at "
                  + file.getAbsolutePath()
                  + ". This should be a file not a directory!");
      return;
    }
    String user = fabricServer.getUsername();
    String password = fabricServer.getPassword();
    if (Strings.isNullOrBlank(user)) {
      getLog()
          .warn(
              "No <username> value defined for the server "
                  + serverId
                  + " in your ~/.m2/settings.xml. Please add a value!");
    }
    if (Strings.isNullOrBlank(password)) {
      getLog()
          .warn(
              "No <password> value defined for the server "
                  + serverId
                  + " in your ~/.m2/settings.xml. Please add a value!");
    }

    Apps.postFileToGit(file, user, password, consoleUrl, branch, deployPath, LOG);
  }
 public KubernetesClient getKubernetes() {
   if (kubernetes == null) {
     String kubernetesAddress = kubernetesUrl.getValue();
     if (Strings.isNotBlank(kubernetesAddress)) {
       kubernetes =
           new DefaultKubernetesClient(
               new ConfigBuilder().withMasterUrl(kubernetesAddress).build());
     } else {
       kubernetes = new DefaultKubernetesClient();
     }
   }
   Objects.notNull(kubernetes, "kubernetes");
   return kubernetes;
 }
Esempio n. 23
0
 /**
  * Returns all the environment variable properties defined in the pom.xml which are prefixed with
  * "fabric8.env."
  */
 public Map<String, String> getEnvironmentVariableProperties() {
   Map<String, String> rawProperties =
       findPropertiesWithPrefix(
           getProject().getProperties(), "fabric8.env.", Strings.toEnvironmentVariableFunction());
   Set<Map.Entry<String, String>> entries = rawProperties.entrySet();
   Map<String, String> answer = new HashMap<>();
   for (Map.Entry<String, String> entry : entries) {
     String key = entry.getKey();
     String value = entry.getValue();
     value = unquoteTemplateExpression(value);
     answer.put(key, value);
   }
   return answer;
 }
Esempio n. 24
0
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    String buildConfigName = buildName.getValue();
    Objects.assertNotNull(buildConfigName, "buildName");
    Map<String, String> labels = BuildConfigs.createBuildLabels(buildConfigName);
    String ouputImageName = imageName.getValue();
    String gitUrlText = getOrFindGitUrl(context, gitUri.getValue());
    String imageText = outputImage.getValue();
    Model mavenModel = getMavenModel(context);
    if (Strings.isNullOrBlank(imageText) && mavenModel != null) {
      imageText = mavenModel.getProperties().getProperty("docker.image");
    }

    String webhookSecretText = webHookSecret.getValue();
    if (Strings.isNullOrBlank(webhookSecretText)) {
      // TODO generate a really good secret!
      webhookSecretText = "secret101";
    }
    BuildConfig buildConfig =
        BuildConfigs.createBuildConfig(
            buildConfigName, labels, gitUrlText, ouputImageName, imageText, webhookSecretText);

    System.out.println("Generated BuildConfig: " + toJson(buildConfig));

    ImageStream imageRepository = BuildConfigs.imageRepository(buildConfigName, labels);

    Controller controller = createController();
    controller.applyImageStream(
        imageRepository, "generated ImageStream: " + toJson(imageRepository));
    controller.applyBuildConfig(buildConfig, "generated BuildConfig: " + toJson(buildConfig));
    return Results.success(
        "Added BuildConfig: "
            + Builds.getName(buildConfig)
            + " to OpenShift at master: "
            + getKubernetes().getAddress());
  }
Esempio n. 25
0
 /**
  * Applies the kubernetes json url to the configuration.
  *
  * @param map The arquillian configuration.
  */
 private static URL getKubernetesConfigurationUrl(Map<String, String> map)
     throws MalformedURLException {
   if (map.containsKey(ENVIRONMENT_CONFIG_URL)) {
     return new URL(map.get(ENVIRONMENT_CONFIG_URL));
   } else if (map.containsKey(ENVIRONMENT_CONFIG_RESOURCE_NAME)) {
     String resourceName = map.get(ENVIRONMENT_CONFIG_RESOURCE_NAME);
     return findConfigResource(resourceName);
   } else if (Strings.isNotBlank(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, ""))) {
     return new URL(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, ""));
   } else {
     String defaultValue = "/" + DEFAULT_CONFIG_FILE_NAME;
     String resourceName =
         Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, defaultValue);
     URL answer = findConfigResource(resourceName);
     if (answer == null) {}
     return answer;
   }
 }
Esempio n. 26
0
  /**
   * Iterates through all nested directories and generates archetypes for all found, non-pom Maven
   * projects.
   *
   * @param baseDir a directory to look for projects which may be converted to Maven Archetypes
   * @param outputDir target directory where Maven Archetype projects will be generated
   * @param clean regenerate the archetypes (clean the archetype target dir)?
   * @throws IOException
   */
  public void generateArchetypes(
      String containerType, File baseDir, File outputDir, boolean clean, List<String> dirs)
      throws IOException {
    LOG.debug(
        "Generating archetypes from {} to {}",
        baseDir.getCanonicalPath(),
        outputDir.getCanonicalPath());
    File[] files = baseDir.listFiles();
    if (files != null) {
      for (File file : files) {
        if (file.isDirectory()) {
          File projectDir = file;
          File projectPom = new File(projectDir, "pom.xml");
          if (projectPom.exists() && !skipImport(projectDir)) {
            if (archetypeUtils.isValidProjectPom(projectPom)) {
              String fileName = file.getName();
              String archetypeDirName = fileName.replace("example", "archetype");
              if (fileName.equals(archetypeDirName)) {
                archetypeDirName += "-archetype";
              }
              archetypeDirName = containerType + "-" + archetypeDirName;

              File archetypeDir = new File(outputDir, archetypeDirName);
              generateArchetype(projectDir, projectPom, archetypeDir, clean, dirs);

              File archetypePom = new File(archetypeDir, "pom.xml");
              if (archetypePom.exists()) {
                addArchetypeMetaData(archetypePom, archetypeDirName);
              }
            } else {
              // lets iterate through the children
              String childContainerType = file.getName();
              if (Strings.isNotBlank(containerType)) {
                childContainerType = containerType + "-" + childContainerType;
              }
              generateArchetypes(childContainerType, file, outputDir, clean, dirs);
            }
          }
        }
      }
    }
  }
Esempio n. 27
0
  protected Iterable<PipelineDTO> getPipelines(UIContext context, boolean filterPipelines) {
    Set<String> builders = null;
    ProjectOverviewDTO projectOveriew = null;
    if (filterPipelines) {
      projectOveriew = getProjectOverview(context);
      builders = projectOveriew.getBuilders();
    }
    File dir = getJenkinsWorkflowFolder(context);
    Set<String> buildersFound = new HashSet<>();
    if (dir != null) {
      Filter<File> filter =
          new Filter<File>() {
            @Override
            public boolean matches(File file) {
              return file.isFile() && Objects.equal(JENKINSFILE, file.getName());
            }
          };
      Set<File> files = Files.findRecursive(dir, filter);
      List<PipelineDTO> pipelines = new ArrayList<>();
      for (File file : files) {
        try {
          String relativePath = Files.getRelativePath(dir, file);
          String value = Strings.stripPrefix(relativePath, "/");
          String label = value;
          String postfix = "/" + JENKINSFILE;
          if (label.endsWith(postfix)) {
            label = label.substring(0, label.length() - postfix.length());
          }
          if (label.startsWith(jenkinsFilePrefix)) {
            label = label.substring(jenkinsFilePrefix.length());
          }
          // Lets ignore the fabric8 specific pipelines
          if (label.startsWith("fabric8-release/")) {
            continue;
          }
          String builder = null;
          int idx = label.indexOf("/");
          if (idx > 0) {
            builder = label.substring(0, idx);
            if (filterPipelines && !builders.contains(builder)) {
              // ignore this builder
              continue;
            } else {
              buildersFound.add(builder);
            }
          }
          String descriptionMarkdown = null;
          File markdownFile = new File(file.getParentFile(), "ReadMe.md");
          if (Files.isFile(markdownFile)) {
            descriptionMarkdown = IOHelpers.readFully(markdownFile);
          }
          PipelineDTO pipeline = new PipelineDTO(value, label, builder, descriptionMarkdown);

          File yamlFile = new File(file.getParentFile(), "metadata.yml");
          if (Files.isFile(yamlFile)) {
            PipelineMetadata metadata = null;
            try {
              metadata = loadYaml(yamlFile, PipelineMetadata.class);
            } catch (IOException e) {
              LOG.warn("Failed to parse yaml file " + yamlFile + ". " + e, e);
            }
            if (metadata != null) {
              metadata.configurePipeline(pipeline);
            }
          }
          pipelines.add(pipeline);
        } catch (IOException e) {
          LOG.warn(
              "Failed to find relative path for folder " + dir + " and file " + file + ". " + e, e);
        }
      }
      if (buildersFound.size() == 1) {
        // lets trim the builder prefix from the labels
        for (String first : buildersFound) {
          String prefix = first + "/";
          for (PipelineDTO pipeline : pipelines) {
            String label = pipeline.getLabel();
            if (label.startsWith(prefix)) {
              label = label.substring(prefix.length());
              pipeline.setLabel(label);
            }
          }
          break;
        }
      }
      Collections.sort(pipelines);
      return pipelines;
    } else {
      LOG.warn("No jenkinsWorkflowFolder!");
      return new ArrayList<>();
    }
  }
Esempio n. 28
0
 protected String getStringAttribute(
     Map<Object, Object> attributeMap, String name, String defaultValue) {
   String answer = getStringAttribute(attributeMap, name);
   return Strings.isNullOrBlank(answer) ? defaultValue : answer;
 }
Esempio n. 29
0
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    LOG.info("Creating the fabric8.yml file");

    String fileName = ProjectConfigs.FILE_NAME;
    Project project = getSelectedProject(context);
    File configFile = getProjectConfigFile(context.getUIContext(), getSelectedProject(context));
    if (configFile == null) {
      // lets not fail as we typically want to execute SaveDevOpsStep next...
      return Results.success();
    }
    ProjectConfig config = null;
    boolean hasFile = false;
    if (configFile.exists()) {
      config = ProjectConfigs.parseProjectConfig(configFile);
      hasFile = true;
    }
    if (config == null) {
      config = new ProjectConfig();
    }

    CommandHelpers.putComponentValuesInAttributeMap(context, inputComponents);
    updateConfiguration(context, config);
    LOG.info("Result: " + config);

    String message;
    if (config.isEmpty() && !hasFile) {
      message = "No " + fileName + " need be generated as there is no configuration";
      return Results.success(message);
    } else {
      String operation = "Updated";
      if (!configFile.exists()) {
        operation = "Created";
      }
      ProjectConfigs.saveConfig(config, configFile);
      message = operation + " " + fileName;
    }

    // now lets update the devops stuff
    UIContext uiContext = context.getUIContext();
    Map<Object, Object> attributeMap = uiContext.getAttributeMap();

    String gitUrl = getStringAttribute(attributeMap, "gitUrl");
    if (Strings.isNullOrBlank(gitUrl)) {
      gitUrl = getStringAttribute(attributeMap, "gitAddress");
    }

    Object object = attributeMap.get(Project.class);
    String user = getStringAttribute(attributeMap, "gitUser");
    String named = getStringAttribute(attributeMap, "projectName");
    ;
    File basedir = CommandHelpers.getBaseDir(project);
    if (basedir == null && configFile != null) {
      basedir = configFile.getParentFile();
    }

    if (object instanceof Project) {
      Project newProject = (Project) object;
      MetadataFacet facet = newProject.getFacet(MetadataFacet.class);
      if (facet != null) {
        if (Strings.isNullOrBlank(named)) {
          named = facet.getProjectName();
        }
        if (Strings.isNullOrBlank(gitUrl)) {
          String address = getStringAttribute(attributeMap, "gitAddress");
          gitUrl = address + user + "/" + named + ".git";
        }
      } else {
        LOG.error("No MetadataFacet for newly created project " + newProject);
      }
    } else {
      // updating an existing project - so lets try find the git url from the current source code
      if (Strings.isNullOrBlank(gitUrl)) {
        gitUrl = GitHelpers.extractGitUrl(basedir);
      }
      if (basedir != null) {
        if (Strings.isNullOrBlank(named)) {
          named = basedir.getName();
        }
      }
    }
    // lets default the environments from the pipeline
    PipelineDTO pipelineValue = pipeline.getValue();
    LOG.info("Using pipeline " + pipelineValue);
    String buildName = config.getBuildName();
    if (Strings.isNotBlank(buildName)) {
      if (pipelineValue != null) {
        List<String> environments = pipelineValue.getEnvironments();
        if (environments == null) {
          environments = new ArrayList<>();
        }
        LinkedHashMap<String, String> environmentMap = new LinkedHashMap<>();
        if (environments.isEmpty()) {
          environmentMap.put("Current", namespace);
        } else {
          for (String environment : environments) {
            String envNamespace = namespace + "-" + environment.toLowerCase();
            environmentMap.put(environment, envNamespace);
          }
        }
        config.setEnvironments(environmentMap);
      }
    }
    LOG.info("Configured project " + buildName + " environments: " + config.getEnvironments());
    ProjectConfigs.defaultEnvironments(config, namespace);

    String projectName = config.getBuildName();
    if (Strings.isNullOrBlank(projectName)) {
      projectName = named;
      config.setBuildName(projectName);
    }

    LOG.info("Project name is: " + projectName);
    if (Strings.isNotBlank(projectName) && project != null) {
      MavenFacet maven = project.getFacet(MavenFacet.class);
      Model pom = maven.getModel();
      if (pom != null
          && !isFunktionParentPom(project)
          && !isFabric8MavenPlugin3OrGreater(project)) {
        Properties properties = pom.getProperties();
        boolean updated = false;
        updated =
            MavenHelpers.updatePomProperty(
                properties, "fabric8.label.project", projectName, updated);
        updated =
            MavenHelpers.updatePomProperty(
                properties, "fabric8.label.version", "${project.version}", updated);
        if (updated) {
          LOG.info("Updating pom.xml properties!");
          maven.setModel(pom);
        } else {
          LOG.warn("Did not update pom.xml properties!");
        }
      } else {
        LOG.warn("No pom.xml found!");
      }
    }

    Boolean copyFlowToProjectValue = copyPipelineToProject.getValue();
    if (copyFlowToProjectValue != null && copyFlowToProjectValue.booleanValue()) {
      if (basedir == null || !basedir.isDirectory()) {
        LOG.warn("Cannot copy the pipeline to the project as no basedir!");
      } else {
        String flow = null;
        PipelineDTO pipelineDTO = pipelineValue;
        if (pipelineDTO != null) {
          flow = pipelineDTO.getValue();
        }
        if (Strings.isNullOrBlank(flow)) {
          LOG.warn("Cannot copy the pipeline to the project as no pipeline selected!");
        } else {
          String flowText = getFlowContent(flow, uiContext);
          if (Strings.isNullOrBlank(flowText)) {
            LOG.warn(
                "Cannot copy the pipeline to the project as no pipeline text could be loaded!");
          } else {
            flowText = Strings.replaceAllWithoutRegex(flowText, "GIT_URL", "'" + gitUrl + "'");
            File newFile = new File(basedir, ProjectConfigs.LOCAL_FLOW_FILE_NAME);
            Files.writeToFile(newFile, flowText.getBytes());
            LOG.info("Written pipeline to " + newFile);
            if (config != null) {
              config.setPipeline(null);
              config.setUseLocalFlow(true);
            }
          }
        }
      }
    }

    final DevOpsConnector connector = new DevOpsConnector();
    connector.setProjectConfig(config);
    connector.setTryLoadConfigFileFromRemoteGit(false);
    connector.setUsername(user);
    connector.setPassword(getStringAttribute(attributeMap, "gitPassword"));
    connector.setBranch(getStringAttribute(attributeMap, "gitBranch", "master"));
    connector.setBasedir(basedir);
    connector.setGitUrl(gitUrl);
    connector.setRepoName(named);

    connector.setRegisterWebHooks(true);

    // lets not trigger the jenkins webhook yet as the git push should trigger the build
    connector.setTriggerJenkinsJob(false);

    LOG.info("Using connector: " + connector);

    /*
            attributeMap.put("registerWebHooks", new Runnable() {
                @Override
                public void run() {
                    LOG.info("Now registering webhooks!");
                    connector.registerWebHooks();
                }
            });
    */
    try {
      connector.execute();
    } catch (Exception e) {
      LOG.error("Failed to update DevOps resources: " + e, e);
    }

    return Results.success(message);
  }
 public void addPod(Pod pod) {
   String id = getId(pod);
   if (Strings.isNotBlank(id)) {
     pods.put(id, pod);
   }
 }