use of org.ovirt.engine.sdk4.Connection in project Payara by payara.
the class SSHLauncher method setupKey.
/**
* Setting up the key involves the following steps:
* -If a key exists and we can connect using the key, do nothing.
* -Generate a key pair if there isn't one
* -Connect to remote host using password auth and do the following:
* 1. create .ssh directory if it doesn't exist
* 2. copy over the key as key.tmp
* 3. Append the key to authorized_keys file
* 4. Remove the temporary key file key.tmp
* 5. Fix permissions for home, .ssh and authorized_keys
* @param node - remote host
* @param pubKeyFile - .pub file
* @param generateKey - flag to indicate if key needs to be generated or not
* @param passwd - ssh user password
* @throws IOException
* @throws InterruptedException
*/
public void setupKey(String node, String pubKeyFile, boolean generateKey, String passwd) throws IOException, InterruptedException {
boolean connected = false;
File key = new File(keyFile);
if (logger.isLoggable(Level.FINER))
logger.finer("Key = " + keyFile);
if (key.exists()) {
if (checkConnection()) {
throw new IOException("SSH public key authentication is already configured for " + userName + "@" + node);
}
} else {
if (generateKey) {
if (!generateKeyPair()) {
throw new IOException("SSH key pair generation failed. Please generate key manually.");
}
} else {
throw new IOException("SSH key pair not present. Please generate a key pair manually or specify an existing one and re-run the command.");
}
}
// password is must for key distribution
if (passwd == null) {
throw new IOException("SSH password is required for distributing the public key. You can specify the SSH password in a password file and pass it through --passwordfile option.");
}
connection = new Connection(node, port);
connection.connect();
connected = connection.authenticateWithPassword(userName, passwd);
if (!connected) {
throw new IOException("SSH password authentication failed for user " + userName + " on host " + node);
}
// We open up a second connection for scp and exec. For some reason, a hang
// is seen in MKS if we try to do everything using the same connection.
Connection conn = new Connection(node, port);
conn.connect();
boolean ret = conn.authenticateWithPassword(userName, passwd);
if (!ret) {
throw new IOException("SSH password authentication failed for user " + userName + " on host " + node);
}
// initiate scp client
SCPClient scp = new SCPClient(conn);
SFTPClient sftp = new SFTPClient(connection);
if (key.exists()) {
// fixes .ssh file mode
setupSSHDir();
if (pubKeyFile == null) {
pubKeyFile = keyFile + ".pub";
}
File pubKey = new File(pubKeyFile);
if (!pubKey.exists()) {
throw new IOException("Public key file " + pubKeyFile + " does not exist.");
}
try {
if (!sftp.exists(SSH_DIR)) {
if (logger.isLoggable(Level.FINE)) {
logger.fine(SSH_DIR + " does not exist");
}
sftp.mkdirs(".ssh", 0700);
}
} catch (Exception e) {
if (logger.isLoggable(Level.FINER)) {
e.printStackTrace();
}
throw new IOException("Error while creating .ssh directory on remote host:" + e.getMessage());
}
// copy over the public key to remote host
scp.put(pubKey.getAbsolutePath(), "key.tmp", ".ssh", "0600");
// append the public key file contents to authorized_keys file on remote host
String mergeCommand = "cd .ssh; cat key.tmp >> " + AUTH_KEY_FILE;
if (logger.isLoggable(Level.FINER)) {
logger.finer("mergeCommand = " + mergeCommand);
}
if (conn.exec(mergeCommand, new ByteArrayOutputStream()) != 0) {
throw new IOException("Failed to propogate the public key " + pubKeyFile + " to " + host);
}
logger.info("Copied keyfile " + pubKeyFile + " to " + userName + "@" + host);
// remove the public key file on remote host
if (conn.exec("rm .ssh/key.tmp", new ByteArrayOutputStream()) != 0) {
logger.warning("WARNING: Failed to remove the public key file key.tmp on remote host " + host);
}
if (logger.isLoggable(Level.FINER)) {
logger.finer("Removed the temporary key file on remote host");
}
// Lets fix all the permissions
// On MKS, chmod doesn't work as expected. StrictMode needs to be disabled
// for connection to go through
logger.info("Fixing file permissions for home(755), .ssh(700) and authorized_keys file(644)");
sftp.chmod(".", 0755);
sftp.chmod(SSH_DIR, 0700);
sftp.chmod(SSH_DIR + AUTH_KEY_FILE, 0644);
// release the connections
sftp.close();
conn.close();
}
}
use of org.ovirt.engine.sdk4.Connection in project MVPFrames by RockyQu.
the class LoggingInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Level level = this.level;
Request request = chain.request();
if (level == Level.NONE) {
return chain.proceed(request);
}
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
// 请求地址
Connection connection = chain.connection();
Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
if (hasRequestBody) {
requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
}
log(requestStartMessage);
// Content-Type
if (hasRequestBody) {
if (requestBody.contentType() != null) {
log("Content-Type: " + requestBody.contentType());
}
if (requestBody.contentLength() != -1) {
log("Content-Length: " + requestBody.contentLength());
}
}
// 拼装请求参数
Headers headers = request.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
String name = headers.name(i);
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
log(name + ": " + headers.value(i));
}
}
// Request结束
if (!hasRequestBody) {
log("--> END " + request.method());
} else if (bodyEncoded(request.headers())) {
log("--> END " + request.method() + " (encoded body omitted)");
} else {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
if (isPlaintext(buffer)) {
log(buffer.readString(charset));
log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
} else {
log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
}
}
// Response开始
long startNs = System.nanoTime();
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
log("<-- HTTP FAILED: " + e);
throw e;
}
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
ResponseBody responseBody = response.body();
long contentLength = responseBody.contentLength();
String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (", " + bodySize + " body") + ')');
headers = response.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
log(headers.name(i) + ": " + headers.value(i));
}
if (!HttpHeaders.hasBody(response)) {
log("<-- END HTTP");
} else if (bodyEncoded(response.headers())) {
log("<-- END HTTP (encoded body omitted)");
} else {
BufferedSource source = responseBody.source();
// Buffer the entire body.
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException e) {
log("Couldn't decode the response body; charset is likely malformed.");
log("<-- END HTTP");
return response;
}
}
if (!isPlaintext(buffer)) {
log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
return response;
}
if (contentLength != 0) {
log(buffer.clone().readString(charset));
}
log("<-- END HTTP (" + buffer.size() + "-byte body)");
}
return response;
}
use of org.ovirt.engine.sdk4.Connection in project ttdj by soonphe.
the class HttpLoggingInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Level level = this.level;
Request request = chain.request();
if (level == Level.NONE) {
return chain.proceed(request);
}
boolean logBody = level == Level.BODY;
boolean logHeaders = logBody || level == Level.HEADERS;
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
Connection connection = chain.connection();
Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol(protocol);
if (!logHeaders && hasRequestBody) {
requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
}
logger.log(requestStartMessage);
if (logHeaders) {
if (hasRequestBody) {
// them to be included (when available) so there values are known.
if (requestBody.contentType() != null) {
logger.log("Content-Type: " + requestBody.contentType());
}
if (requestBody.contentLength() != -1) {
logger.log("Content-Length: " + requestBody.contentLength());
}
}
Headers headers = request.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
String name = headers.name(i);
// Skip headers from the request body as they are explicitly logged above.
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
logger.log(name + ": " + headers.value(i));
}
}
if (!logBody || !hasRequestBody) {
logger.log("--> END " + request.method());
} else if (bodyEncoded(request.headers())) {
logger.log("--> END " + request.method() + " (encoded body omitted)");
} else {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
logger.log("");
logger.log(buffer.readString(charset));
logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
}
}
long startNs = System.nanoTime();
Response response = chain.proceed(request);
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
ResponseBody responseBody = response.body();
long contentLength = responseBody.contentLength();
String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
if (logHeaders) {
Headers headers = response.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
logger.log(headers.name(i) + ": " + headers.value(i));
}
if (!logBody || !HttpHeaders.hasBody(response)) {
logger.log("<-- END HTTP");
} else if (bodyEncoded(response.headers())) {
logger.log("<-- END HTTP (encoded body omitted)");
} else {
BufferedSource source = responseBody.source();
// Buffer the entire body.
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
if (contentLength != 0) {
logger.log("");
logger.log(buffer.clone().readString(charset));
}
logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
}
}
return response;
}
use of org.ovirt.engine.sdk4.Connection in project ovirt-engine-sdk-java by oVirt.
the class UpdateDataCenter method main.
public static void main(String[] args) throws Exception {
// Create the connection to the server:
Connection connection = connection().url("https://engine40.example.com/ovirt-engine/api").user("admin@internal").password("redhat123").trustStoreFile("truststore.jks").build();
// Get the reference to the data centers service:
DataCentersService dcsService = connection.systemService().dataCentersService();
// Retrieve the description of the data center:
DataCenter dc = dcsService.list().search("name=mydc").send().dataCenters().get(0);
// In order to update the data center we need a reference to the service that manages it, then we can call the
// "update" method passing the update:
DataCenterService dcService = dcsService.dataCenterService(dc.id());
dc = dcService.update().dataCenter(dataCenter().description("Updated description")).send().dataCenter();
// Print the description of the result of the update:
System.out.printf("%s: %s", dc.name(), dc.description());
// Close the connection to the server:
connection.close();
}
use of org.ovirt.engine.sdk4.Connection in project ovirt-engine-sdk-java by oVirt.
the class UpdateFencingOptions method main.
public static void main(String[] args) throws Exception {
// Create the connection to the server:
Connection connection = connection().url("https://engine40.example.com/ovirt-engine/api").user("admin@internal").password("redhat123").trustStoreFile("truststore.jks").build();
// The name and value of the option that we want to add or update:
String name = "lanplus";
String value = "1";
// Get the reference to the service that manages the hosts:
HostsService hostsService = connection.systemService().hostsService();
// Find the host:
Host host = hostsService.list().search("name=myhost").send().hosts().get(0);
// Get the reference to the service that manages the fencing agents used by the host that we found in the
// previous step:
HostService hostService = hostsService.hostService(host.id());
FenceAgentsService agentsService = hostService.fenceAgentsService();
// The host may have multiple fencing agents, so we need to locate the first of type 'ipmilan':
List<Agent> agents = agentsService.list().send().agents();
Agent agent = null;
for (Agent x : agents) {
if ("ipmlan".equals(x.type())) {
agent = x;
break;
}
}
// Get the options of the fencing agent. There may be no options, in that case we need to use an empty list.
List<Option> original = agent.options();
if (original == null) {
original = Collections.emptyList();
}
// Create a list of modified options, containing all the original options except the one with the name we want
// to modify, as we will add that with the right value later:
List<Option> modified = new ArrayList<>();
for (Option option : original) {
if (!name.equals(option.name())) {
modified.add(option);
}
}
// Add the modified option to the list of modified options:
Option option = option().name(name).value(value).build();
modified.add(option);
// Find the service that manages the fence agent:
FenceAgentService agentService = agentsService.agentService(agent.id());
// Send the update request containing the modified list of options:
agentService.update().agent(agent().options(modified)).send();
// Close the connection to the server:
connection.close();
}
Aggregations