Skip to content

Commit

Permalink
fix : tunneling 코드, yml 파일 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
genius00hwan committed Nov 23, 2024
1 parent 3c65f23 commit 542a319
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 76 deletions.
76 changes: 32 additions & 44 deletions src/main/java/icurriculum/global/config/SSHConfig.java
Original file line number Diff line number Diff line change
@@ -1,42 +1,33 @@
package icurriculum.global.config;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import jakarta.annotation.PreDestroy;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.net.Socket;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

@Slf4j
@Configuration
@Component
@ConfigurationProperties(prefix = "ssh")
@Validated
@Setter
@Getter
public class SSHConfig {



@Value("${ec2.remote_jump_host}")
private String sshHost;

@Value("${ec2.ssh_port}")
@Value("${cloud.aws.ec2.remote_jump_host}")
private String remoteJumpHost;
@Value("${cloud.aws.ec2.ssh_port}")
private int sshPort;

@Value("${ec2.user}")
private String sshUser;

@Value("${ec2.private_key_path}")
@Value("${cloud.aws.ec2.user}")
private String user;
@Value("${cloud.aws.ec2.private_key_path}")
private String privateKeyPath;

@Value("${ec2.database_endpoint}")
private String remoteHost;

@Value("${ec2.database_port}")
private int remotePort;


private Session session;

@PreDestroy
Expand All @@ -46,35 +37,32 @@ public void destroy() {
}
}


public Integer buildSshConnection() {
public Integer buildSshConnection(String endpoint, int port) {
Integer forwardPort = null;
try {

try {
log.info("SSH {}@{}:{} with {}", user, remoteJumpHost, sshPort, privateKeyPath);
JSch jsch = new JSch();

jsch.addIdentity(privateKeyPath);
session = jsch.getSession(sshUser, sshHost, sshPort);
session = jsch.getSession(user, remoteJumpHost, sshPort);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();

// SSH 터널 설정
forwardPort = session.setPortForwardingL(0, remoteHost, remotePort);



} catch (Exception e) {
System.err.println("SSH 터널 연결 실패: " + e.getMessage());
log.info("Starting SSH session connection...");
session.connect();
log.info("SSH session connected");

forwardPort = session.setPortForwardingL(0, endpoint, port);
log.info("ssh tunnel to {}:{}",endpoint,port);
log.info("Port forwarding created on local port {} to remote port {}", forwardPort,
port);
} catch (JSchException e) {
log.error(e.getMessage());
this.destroy();
throw new RuntimeException(e);
}
return forwardPort;
}

private boolean isLocalPortOpen(int port) {
try (Socket socket = new Socket("localhost", port)) {
return true; // 연결 성공, 포트가 열려 있음
} catch (IOException e) {
return false; // 연결 실패, 포트가 열려 있지 않음
}
}
}

}
82 changes: 50 additions & 32 deletions src/main/java/icurriculum/global/config/SSHMongoConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,62 +4,80 @@
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import icurriculum.global.config.SSHConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class SSHMongoConfig {
@Value("${spring.data.mongodb.username}")
private String mongoUsername;

@Value("${spring.data.mongodb.password}")
private String mongoPassword;
private final SSHConfig initializer;

@Value("${spring.data.mongodb.host}")
private String mongoHost;
@Value("${server}")
private String isServer;

@Value("${cloud.aws.ec2.database_endpoint}")
private String databaseEndpoint;

private final SSHConfig sshConfig; // SSHConfig 클래스 사용
private final MongoProperties mongoProperties; // MongoDB 프로퍼티
@Value("${cloud.aws.ec2.database_port}")
private int databasePort;

@Value("${spring.data.mongodb.username}")
private String mongoUser;
@Value("${spring.data.mongodb.password}")
private String mongoPassword;

@Value("${spring.data.mongodb.database}")
private String databaseName;

@Bean
@Primary
public MongoClient mongoClient() {
Integer forwardedPort = sshConfig.buildSshConnection(); // SSHConfig에서 로컬 포트 가져오기
String connectionString = String.format(
"mongodb://%s:%s@%s:%d/?readPreference=secondaryPreferred&retryWrites=false",
mongoUsername,
mongoPassword,
mongoHost,
forwardedPort); // MongoDB URI 구성
String host = databaseEndpoint;
int port = databasePort;

if (isServer.equals("false")) {
Integer forwardedPort = initializer.buildSshConnection(databaseEndpoint, databasePort);
host = "localhost";
port = forwardedPort;
}

log.info("MongoDB Connection String: {}", connectionString);
try {
ConnectionString connectionString = new ConnectionString(String.format(
"mongodb://%s:%s@%s:%s/%s?readPreference=secondaryPreferred&retryWrites=false",
mongoUser,
mongoPassword,
host,
port,
databaseName
));

// MongoClientSettings 생성
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(connectionString)) // MongoDB 연결 문자열 적용
.build();
MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();

// MongoClient 생성
MongoClient client = MongoClients.create(settings);
log.info("mongo connection through SSH: host={}, port={}", host, port);


return client; // MongoClient 반환
return MongoClients.create(mongoClientSettings);
} catch (Exception e) {
log.error("Failed to create MongoClient: {}", e.getMessage(), e);
throw e; // 예외를 던져서 초기화가 실패하도록 함
}
}

@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), "demo"); // 여기서 demo 데이터베이스 지정
public MongoTemplate mongoTemplate(MongoClient mongoClient) {
MongoDatabaseFactory mongoDbFactory = new SimpleMongoClientDatabaseFactory(mongoClient, databaseName);
return new MongoTemplate(mongoDbFactory);
}
}

}

0 comments on commit 542a319

Please sign in to comment.