Skip to content

Commit

Permalink
Merge pull request #1506 from rohanKanojia/pr/custom-resource-example
Browse files Browse the repository at this point in the history
  • Loading branch information
fusesource-ci authored May 2, 2019
2 parents a6e967b + fc29412 commit 94bba0b
Show file tree
Hide file tree
Showing 7 changed files with 666 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
* Fix #1507: remove unnecessary OutputStream copying a directory and return the directory object instead the file object when a directory is copied or read

Improvements

* Added example for raw custom resources.

Dependency Upgrade

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext;
import io.fabric8.kubernetes.client.dsl.base.OperationSupport;
import io.fabric8.kubernetes.client.utils.IOHelpers;
import io.fabric8.kubernetes.client.utils.Utils;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
Expand All @@ -31,26 +32,42 @@
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RawCustomResourceOperationsImpl extends OperationSupport {
private OkHttpClient client;
private Config config;
private CustomResourceDefinitionContext customResourceDefinition;
private ObjectMapper objectMapper;

private enum HttpCallMethod { GET, POST, PUT, DELETE };

public RawCustomResourceOperationsImpl(OkHttpClient client, Config config, CustomResourceDefinitionContext customResourceDefinition) {
this.client = client;
this.config = config;
this.customResourceDefinition = customResourceDefinition;
this.objectMapper = new ObjectMapper();
}

public Map<String, Object> load(InputStream fileInputStream) throws IOException {
String objectAsString = IOHelpers.readFully(fileInputStream);
HashMap<String, Object> retVal = null;
if (IOHelpers.isJSONValid(objectAsString)) {
retVal = objectMapper.readValue(objectAsString, HashMap.class);
} else {
retVal = objectMapper.readValue(IOHelpers.convertYamlToJson(objectAsString), HashMap.class);
}
return retVal;
}

public Map<String, Object> create(String objectAsString) throws IOException {
return validateAndSubmitRequest(null, null, objectAsString, HttpCallMethod.POST);
}

public Map<String, Object> create(Map<String, Object> object) throws KubernetesClientException, IOException {
return validateAndSubmitRequest(null, null, objectMapper.writeValueAsString(object), HttpCallMethod.POST);
}

public Map<String, Object> create(String namespace, String objectAsString) throws KubernetesClientException, IOException {
return validateAndSubmitRequest(namespace, null, objectAsString, HttpCallMethod.POST);
}
Expand All @@ -63,14 +80,30 @@ public Map<String, Object> create(String namespace, InputStream objectAsStream)
return validateAndSubmitRequest(namespace, null, IOHelpers.readFully(objectAsStream), HttpCallMethod.POST);
}

public Map<String, Object> create(String namespace, Map<String, Object> object) throws KubernetesClientException, IOException {
return validateAndSubmitRequest(namespace, null, objectMapper.writeValueAsString(object), HttpCallMethod.POST);
}

public Map<String, Object> edit(String name, Map<String, Object> object) throws IOException {
return validateAndSubmitRequest(null, name, objectMapper.writeValueAsString(object), HttpCallMethod.PUT);
}

public Map<String, Object> edit(String name, String objectAsString) throws IOException {
return validateAndSubmitRequest(null, name, objectAsString, HttpCallMethod.PUT);
}

public Map<String, Object> edit(String namespace, String name, Map<String, Object> object) throws IOException {
return validateAndSubmitRequest(namespace, name, objectMapper.writeValueAsString(object), HttpCallMethod.PUT);
}

public Map<String, Object> edit(String namespace, String name, String objectAsString) throws IOException {
return validateAndSubmitRequest(namespace, name, objectAsString, HttpCallMethod.PUT);
}

public Map<String, Object> edit(String name, InputStream objectAsStream) throws IOException, KubernetesClientException {
return validateAndSubmitRequest(null, name, IOHelpers.readFully(objectAsStream), HttpCallMethod.PUT);
}

public Map<String, Object> edit(String namespace, String name, InputStream objectAsStream) throws IOException, KubernetesClientException {
return validateAndSubmitRequest(namespace, name, IOHelpers.readFully(objectAsStream), HttpCallMethod.PUT);
}
Expand Down Expand Up @@ -116,6 +149,7 @@ private String fetchUrl(String namespace, Map<String, String> labels) {
}
urlBuilder.append(customResourceDefinition.getPlural()).append("/");
if(labels != null) {
urlBuilder.deleteCharAt(urlBuilder.lastIndexOf("/"));
urlBuilder.append("?labelSelector").append("=").append(getLabelsQueryParam(labels));
}
return urlBuilder.toString();
Expand All @@ -127,7 +161,7 @@ private String getLabelsQueryParam(Map<String, String> labels) {
if(labelQueryBuilder.length() > 0) {
labelQueryBuilder.append(",");
}
labelQueryBuilder.append(entry.getKey()).append("=").append(entry.getValue());
labelQueryBuilder.append(entry.getKey()).append(Utils.toUrlEncoded("=")).append(entry.getValue());
}
return labelQueryBuilder.toString();
}
Expand All @@ -144,10 +178,14 @@ private Map<String, Object> makeCall(String url, String body, HttpCallMethod cal
if(response.code() != HttpURLConnection.HTTP_NOT_FOUND &&
response.code() != HttpURLConnection.HTTP_SERVER_ERROR &&
response.code() != HttpURLConnection.HTTP_BAD_REQUEST) {
return new ObjectMapper().readValue(response.body().string(), HashMap.class);
return objectMapper.readValue(response.body().string(), HashMap.class);
} else {
response.close();
throw new IllegalStateException(response.message());
if(response.body() != null) {
throw new KubernetesClientException(response.body().string());
} else {
response.close();
throw new KubernetesClientException(response.message());
}
}
} catch(Exception e) {
throw KubernetesClientException.launderThrowable(e);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.examples;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class RawCustomResourceExample {
private static final Logger logger = LoggerFactory.getLogger(RawCustomResourceExample.class);

public static void main(String args[]) throws IOException {

try (final KubernetesClient client = new DefaultKubernetesClient()) {
CustomResourceDefinition prometheousRuleCrd = client.customResourceDefinitions().load(RawCustomResourceExample.class.getResourceAsStream("/prometheous-rule-crd.yml")).get();
client.customResourceDefinitions().create(prometheousRuleCrd);
log("Successfully created prometheous custom resource definition");

// Creating Custom Resources Now:
CustomResourceDefinitionContext crdContext = new CustomResourceDefinitionContext.Builder()
.withGroup("monitoring.coreos.com")
.withPlural("prometheusrules")
.withScope("Namespaced")
.withVersion("v1")
.build();

client.customResource(crdContext).create("myproject", RawCustomResourceExample.class.getResourceAsStream("/prometheous-rule-cr.yml"));
log("Created Custom Resource successfully too");

// Listing all custom resources in given namespace:
Map<String, Object> list = client.customResource(crdContext).list("myproject");
List<Map<String, Object>> items = (List<Map<String, Object>>) list.get("items");
log("Custom Resources :- ");
for(Map<String, Object> customResource : items) {
Map<String, Object> metadata = (Map<String, Object>) customResource.get("metadata");
log(metadata.get("name").toString());
}

// Cleanup
log("Deleting custom resources...");
Map<String, Object> deleted = client.customResource(crdContext).delete("myproject", "prometheus-example-rules");
client.customResourceDefinitions().withName("prometheusrules.monitoring.coreos.com").delete();

} catch (KubernetesClientException e) {
e.printStackTrace();
log("Could not create resource", e.getMessage());
}
}

private static void log(String action, Object obj) {
logger.info("{}: {}", action, obj);
}

private static void log(String action) {
logger.info(action);
}
}
30 changes: 30 additions & 0 deletions kubernetes-examples/src/main/resources/prometheous-rule-cr.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
creationTimestamp: null
labels:
prometheus: example
role: alert-rules
name: prometheus-example-rules
spec:
groups:
- name: ./example.rules
rules:
- alert: ExampleAlert
expr: vector(1)
Loading

0 comments on commit 94bba0b

Please sign in to comment.