本文整理汇总了Java中io.fabric8.openshift.client.OpenShiftClient类的典型用法代码示例。如果您正苦于以下问题:Java OpenShiftClient类的具体用法?Java OpenShiftClient怎么用?Java OpenShiftClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
OpenShiftClient类属于io.fabric8.openshift.client包,在下文中一共展示了OpenShiftClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getUserName
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
/**
* Returns the current users kubernetes/openshift user name
*/
public String getUserName() {
OpenShiftClient oc = getOpenShiftClientOrNull();
if (oc != null) {
User user = oc.users().withName("~").get();
if (user == null) {
LOG.warn("Failed to find current logged in user!");
} else {
String answer = KubernetesHelper.getName(user);
if (Strings.isNullOrBlank(answer)) {
LOG.warn("No name for User " + user);
} else {
return answer;
}
}
}
// TODO needs to use the current token to find the current user name
return Configs.currentUserName();
}
示例2: onRequest
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
@Override
public SpeechletResponse onRequest(IntentRequest request, Session session) throws SpeechletException {
if (!getKubernetesClient().isAdaptable(OpenShiftClient.class)) {
return newFailureNotice("Your cluster is not Openshift!");
}
IntentContext<BaseOperation<DeploymentConfig, DeploymentConfigList, ?, ?>> ctx = createContext(request.getIntent(), session);
String namespace = ctx.getVariable(Variable.Namespace, getKubernetesClient().getNamespace());
LOGGER.info("Listing all deployment configs for namespace:" + namespace);
try {
List<String> deployments = list(ctx)
.getItems()
.stream()
.map(d -> d.getMetadata().getName()).collect(Collectors.toList());
if (deployments.isEmpty()) {
return newResponse("No deployment configs found.");
} else {
return newResponse("The available deployment configs are: " + join(deployments, ","));
}
} catch (KubernetesClientException e) {
return newFailureNotice(e.getStatus().getMessage());
}
}
示例3: onRequest
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
@Override
public SpeechletResponse onRequest(IntentRequest request, Session session) throws SpeechletException {
if (!getKubernetesClient().isAdaptable(OpenShiftClient.class)) {
return newFailureNotice("Your cluster is not Openshift!");
}
IntentContext<BaseOperation<Project, ProjectList, ?, ?>> ctx = createContext(request.getIntent(), session);
LOGGER.info("Listing all projects.");
try {
List<String> projects = list(ctx)
.getItems()
.stream()
.map(d -> d.getMetadata().getName()).collect(Collectors.toList());
if (projects.isEmpty()) {
return newResponse("No projects found.");
} else {
return newResponse("The available projects are: " + join(projects, ","));
}
} catch (KubernetesClientException e) {
return newFailureNotice(e.getStatus().getMessage());
}
}
示例4: selectNamespace
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
/**
* Choose a namespace that sounds like the specified namespace.
* @param client The client instance to use to query namespaces.
* @param namespace The specified namespace.
* @return The closest namespace if resemblance is over 80%, else null.
*/
public static final String selectNamespace(KubernetesClient client, String namespace) {
if (client.isAdaptable(OpenShiftClient.class)) {
return selectName(client.adapt(OpenShiftClient.class).projects()
.list()
.getItems()
.stream()
.map(n -> n.getMetadata().getName()), namespace);
} else {
return selectName(client.namespaces()
.list()
.getItems()
.stream()
.map(n -> n.getMetadata().getName()), namespace);
}
}
示例5: setup
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
@BeforeClass
public static void setup() throws IOException {
OpenShiftClient oc = new DefaultOpenShiftClient();
List<Route> routes = oc.routes().inNamespace(oc.getNamespace()).list().getItems();
String ssoAuthUrl = routes.stream()
.filter(r -> "secure-sso".equals(r.getMetadata().getName()))
.findFirst()
.map(r -> "https://" + r.getSpec().getHost())
.orElseThrow(() -> new IllegalStateException("Couldn't find secure-sso route"));
InputStream configStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("keycloak.json");
if (configStream == null) {
throw new IllegalStateException("Could not find any keycloak.json file in classpath.");
}
System.setProperty("sso.auth.server.url", ssoAuthUrl);
Configuration config = JsonSerialization.readValue(configStream, Configuration.class, true);
authzClient = AuthzClient.create(config);
applicationUrls = routes.stream()
.filter(r -> r.getMetadata().getName().contains("secured"))
.map(r -> "http://" + r.getSpec().getHost())
.collect(toList());
}
示例6: getUrl
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
public String getUrl(final OpenShiftClient client, final String namespace) throws RouteNotFoundException {
Route route = getRouteByName(client, namespace, cheRoute);
if (route == null) {
LOG.warn("Route '" + cheRoute + "' not found. Trying to get '" + cheHostRoute + "' route");
route = getRouteByName(client, namespace, cheHostRoute);
}
if (route != null) {
String host = route.getSpec().getHost();
String protocol = getProtocol(route);
LOG.info("Host '{}' has been found", host);
LOG.info("Route protocol '{}'", protocol);
return protocol + "://" + host;
}
throw new RouteNotFoundException(
"Routes '" + cheRoute + "'/'" + cheHostRoute + "' not found in '" + namespace + "' namespace");
}
示例7: getCheServerInfoForMultiTenant
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
private CheServerInfo getCheServerInfoForMultiTenant(OpenShiftClient client, String namespace, String requestURL,
String keycloakToken) {
if (cheDeploymentConfig.deploymentExists(client, namespace) && !migrationCongigMap.exists(client, namespace)) {
// user is supposed to be multi-tenant but still has single-tenant che-server in *-che namespace,
// and does not have 'migration' cm, so update tenant must be called
tenanUpdater.update(keycloakToken);
// wait 10 seconds to be sure that 'migration' cm would be created - indication that migration has started
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// migration has just started
return CheServerHelper.generateCheServerInfo(false, requestURL, true);
} else if (migrationPod.exists(client, namespace)
&& (!migrationPod.isReady(client, namespace) || migrationPod.isRunning(client, namespace))) {
// migration is in progress
return CheServerHelper.generateCheServerInfo(false, requestURL, true);
} else if (migrationPod.isTerminated(client, namespace)) {
// migration has been already done
return CheServerHelper.generateCheServerInfo(true, requestURL, true);
} else {
// Should only happen if migration pod have been removed manually
return CheServerHelper.generateCheServerInfo(true, requestURL, true);
}
}
示例8: getNamespaceOrUseDefault
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
/**
* Gets the current namespace running Jenkins inside or returns a reasonable
* default
*
* @param configuredNamespaces
* the optional configured namespace(s)
* @param client
* the OpenShift client
* @return the default namespace using either the configuration value, the
* default namespace on the client or "default"
*/
public static String[] getNamespaceOrUseDefault(String[] configuredNamespaces, OpenShiftClient client) {
String[] namespaces = configuredNamespaces;
if (namespaces != null) {
for (int i = 0; i < namespaces.length; i++) {
if (namespaces[i].startsWith("${") && namespaces[i].endsWith("}")) {
String envVar = namespaces[i].substring(2, namespaces[i].length() - 1);
namespaces[i] = System.getenv(envVar);
if (StringUtils.isBlank(namespaces[i])) {
logger.warning("No value defined for namespace environment variable `" + envVar + "`");
}
}
}
}
if (namespaces == null || namespaces.length == 0) {
namespaces = new String[] { client.getNamespace() };
if (StringUtils.isBlank(namespaces[0])) {
namespaces = new String[] { OPENSHIFT_DEFAULT_NAMESPACE };
}
}
return namespaces;
}
示例9: updateEndpoints
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
private void updateEndpoints(AddressSpace.Builder builder) throws IOException {
Map<String, String> annotations = new HashMap<>();
annotations.put(AnnotationKeys.ADDRESS_SPACE, builder.getName());
List<Endpoint> endpoints;
/* Watch for routes and lb services */
if (client.isAdaptable(OpenShiftClient.class)) {
endpoints = client.routes().inNamespace(builder.getNamespace()).list().getItems().stream()
.filter(route -> isPartOfAddressSpace(builder.getName(), route))
.map(this::routeToEndpoint)
.collect(Collectors.toList());
} else {
endpoints = client.services().inNamespace(builder.getNamespace()).withLabel(LabelKeys.TYPE, "loadbalancer").list().getItems().stream()
.filter(service -> isPartOfAddressSpace(builder.getName(), service))
.map(this::serviceToEndpoint)
.collect(Collectors.toList());
}
log.debug("Updating endpoints for " + builder.getName() + " to " + endpoints);
builder.setEndpointList(endpoints);
}
示例10: createSecretFromCertAndKeyFiles
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
private static Secret createSecretFromCertAndKeyFiles(final String secretName,
final String namespace,
final String keyKey,
final String certKey,
final File keyFile,
final File certFile,
final OpenShiftClient client)
throws IOException {
Map<String, String> data = new LinkedHashMap<>();
Base64.Encoder encoder = Base64.getEncoder();
data.put(keyKey, encoder.encodeToString(FileUtils.readFileToByteArray(keyFile)));
data.put(certKey, encoder.encodeToString(FileUtils.readFileToByteArray(certFile)));
return client.secrets().inNamespace(namespace).withName(secretName).createOrReplaceWithNew()
.editOrNewMetadata()
.withName(secretName)
.endMetadata()
.addToData(data)
.done();
}
示例11: listAddressSpaces
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
@Override
public Set<NamespaceInfo> listAddressSpaces() {
Map<String, String> labels = new LinkedHashMap<>();
labels.put(LabelKeys.APP, "enmasse");
labels.put(LabelKeys.TYPE, "namespace");
labels.put(LabelKeys.ENVIRONMENT, environment);
if (client.isAdaptable(OpenShiftClient.class)) {
return client.configMaps().inNamespace(namespace).withLabels(labels).list().getItems().stream()
.map(n -> new NamespaceInfo(n.getMetadata().getAnnotations().get(AnnotationKeys.ADDRESS_SPACE),
n.getMetadata().getName(),
n.getMetadata().getAnnotations().get(AnnotationKeys.CREATED_BY)))
.collect(Collectors.toSet());
} else {
return client.namespaces().withLabels(labels).list().getItems().stream()
.map(n -> new NamespaceInfo(n.getMetadata().getAnnotations().get(AnnotationKeys.ADDRESS_SPACE),
n.getMetadata().getName(),
n.getMetadata().getAnnotations().get(AnnotationKeys.CREATED_BY)))
.collect(Collectors.toSet());
}
}
示例12: doGetBuildConfig
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
protected void doGetBuildConfig(Exchange exchange, String operation) throws Exception {
BuildConfig buildConfig = null;
String buildConfigName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_BUILD_CONFIG_NAME,
String.class);
String namespaceName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);
if (ObjectHelper.isEmpty(buildConfigName)) {
LOG.error("Get a specific Build Config require specify a Build Config name");
throw new IllegalArgumentException("Get a specific Build Config require specify a Build Config name");
}
if (ObjectHelper.isEmpty(namespaceName)) {
LOG.error("Get a specific Build Config require specify a namespace name");
throw new IllegalArgumentException("Get a specific Build Config require specify a namespace name");
}
buildConfig = getEndpoint().getKubernetesClient().adapt(OpenShiftClient.class).buildConfigs()
.inNamespace(namespaceName).withName(buildConfigName).get();
exchange.getOut().setBody(buildConfig);
}
示例13: doGetBuild
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
protected void doGetBuild(Exchange exchange, String operation) throws Exception {
Build build = null;
String buildName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_BUILD_NAME, String.class);
String namespaceName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);
if (ObjectHelper.isEmpty(buildName)) {
LOG.error("Get a specific Build require specify a Build name");
throw new IllegalArgumentException("Get a specific Build require specify a Build name");
}
if (ObjectHelper.isEmpty(namespaceName)) {
LOG.error("Get a specific Build require specify a namespace name");
throw new IllegalArgumentException("Get a specific Build require specify a namespace name");
}
build = getEndpoint().getKubernetesClient().adapt(OpenShiftClient.class).builds().inNamespace(namespaceName)
.withName(buildName).get();
exchange.getOut().setBody(build);
}
示例14: validate
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
@Override
public void validate(UIValidationContext context) {
if (github == null || !github.isDetailsValid()) {
// invoked too early before the github account is setup - lets return silently
return;
}
Iterable<GitRepositoryDTO> value = gitRepositoryPattern.getValue();
if (!value.iterator().hasNext()) {
context.addValidationError(gitRepositoryPattern, "You must select a repository to import");
}
// Check for repos with already existing bc
Controller controller = new Controller(kubernetesClientHelper.getKubernetesClient());
OpenShiftClient openShiftClient = controller.getOpenShiftClientOrNull();
if (openShiftClient == null) {
context.addValidationError(gitRepositoryPattern, "Could not create OpenShiftClient. Maybe the Kubernetes server version is older than 1.7?");
}
Iterator<GitRepositoryDTO> it = value.iterator();
String userNameSpace = Tenants.findDefaultUserNamespace(namespaces);
if (userNameSpace == null) {
// Tenant not yet initialised properly!
return;
}
while (it.hasNext()) {
GitRepositoryDTO repo = it.next();
if (repo != null && repo.getName() != null) {
BuildConfig oldBC = openShiftClient.buildConfigs().inNamespace(userNameSpace).withName(repo.getName().toLowerCase()).get();
if (oldBC != null && Strings.isNotBlank(KubernetesHelper.getName(oldBC))) {
context.addValidationError(gitRepositoryPattern, "The repository " + repo.getName() + " has already a build config, please select another repo.");
break;
}
}
}
}
示例15: get
import io.fabric8.openshift.client.OpenShiftClient; //导入依赖的package包/类
/**
* Gets OpenShift client. When using, you are responsible for closing it.
* @param masterUrl URL of OpenShift master
* @param token authorization token
* @return OpenShift client
*/
public OpenShiftClient get(String masterUrl, String token) {
if (fabric8PlatformDevMode) {
LOG.info("Using default OpenShift Client for 'fabric8-platform' deployment on minishift");
return new DefaultOpenShiftClient();
}
LOG.info("Certificate file: {}", caCertFile);
Config config = (StringUtils.isBlank(caCertFile))
? new ConfigBuilder().withMasterUrl(masterUrl).withOauthToken(token).build()
: new ConfigBuilder().withMasterUrl(masterUrl).withOauthToken(token).withCaCertFile(caCertFile).build();
return new DefaultOpenShiftClient(config);
}