diff --git a/src/main/java/icurriculum/global/config/SSHConfig.java b/src/main/java/icurriculum/global/config/SSHConfig.java index ea606bf..7ac4e8e 100644 --- a/src/main/java/icurriculum/global/config/SSHConfig.java +++ b/src/main/java/icurriculum/global/config/SSHConfig.java @@ -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 @@ -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; // 연결 실패, 포트가 열려 있지 않음 - } - } -} + +} \ No newline at end of file diff --git a/src/main/java/icurriculum/global/config/SSHMongoConfig.java b/src/main/java/icurriculum/global/config/SSHMongoConfig.java index e8cad4f..fbedafa 100644 --- a/src/main/java/icurriculum/global/config/SSHMongoConfig.java +++ b/src/main/java/icurriculum/global/config/SSHMongoConfig.java @@ -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); } -} \ No newline at end of file + +} +