<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by flangdu on Medium]]></title>
        <description><![CDATA[Stories by flangdu on Medium]]></description>
        <link>https://medium.com/@hyper201286?source=rss-619cbfeff5b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LUsHeJ-Gp4J1HQgDi15aTg.png</url>
            <title>Stories by flangdu on Medium</title>
            <link>https://medium.com/@hyper201286?source=rss-619cbfeff5b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:22:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hyper201286/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[블로그 이사갑니다]]></title>
            <link>https://medium.com/@hyper201286/%EB%B8%94%EB%A1%9C%EA%B7%B8-%EC%9D%B4%EC%82%AC%EA%B0%91%EB%8B%88%EB%8B%A4-838e88a9f981?source=rss-619cbfeff5b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/838e88a9f981</guid>
            <dc:creator><![CDATA[flangdu]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 13:02:16 GMT</pubDate>
            <atom:updated>2026-03-21T13:02:16.993Z</atom:updated>
            <content:encoded><![CDATA[<p>github 블로그로 이사갑니다. argocd를 쓰다보니 medium은 블로그를 gitops로 운영할 수 없고 md파일 형식 지원이 부족해서 github으로 이사갑니다.</p><p>새로운 블로그 주소입니다.</p><p><a href="https://atgane.github.io/">https://atgane.github.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838e88a9f981" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[vitess 분석: vitess의 mysql 프로토콜 처리]]></title>
            <link>https://medium.com/@hyper201286/vitess-%EB%B6%84%EC%84%9D-vitess%EC%9D%98-mysql-%ED%94%84%EB%A1%9C%ED%86%A0%EC%BD%9C-%EC%B2%98%EB%A6%AC-ab87c95557b8?source=rss-619cbfeff5b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab87c95557b8</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[flangdu]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 11:52:02 GMT</pubDate>
            <atom:updated>2025-06-02T11:52:02.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_YaqzuycFOLKKzDRkOWZQ.png" /></figure><p>이전 아티클에서 vitess에 연결된 커넥션은 listener의 handle메서드에서 처리된다는 것을 알았습니다. 이번에는 해당 함수 내부를 자세히 분석해보도록 하겠습니다(최근에 바빠져서 vitess를 많이 못 다룰 것 같기도 합니다😢).</p><h3>handle메서드 내부</h3><p>Listener의 handle함수는 커넥션에 대한 처리를 가장 먼저 수행하는 함수입니다. 이 함수는 mysql 프로토콜 연결 수립, 인증, 쿼리 전 과정을 담당하는 per-connection 루틴입니다.</p><pre>// https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/mysql/server.go#L363<br>// handle is called in a go routine for each client connection.<br>// FIXME(alainjobart) handle per-connection logs in a way that makes sense.<br>func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Time) {<br> // ✅ 1. 서버 커넥션 생성: 연결 하나의 상태 및 R/W관리<br> c := newServerConn(conn, l)<br> c.ConnectionID = connectionID<br> <br> // ...<br><br> // ✅ 2. listener의 handler에게 connection 생성 이벤트 전달<br> // Tell the handler about the connection coming and going.<br> l.handler.NewConnection(c)<br> defer l.handler.ConnectionClosed(c)<br><br> // Adjust the count of open connections<br> defer connCount.Add(-1)<br><br> // ✅ 핸드셰이크 V10 패킷: mysql 프로토콜 첫 패킷<br> // 서버 버전 / 랜덤 string / auth plugin 등 정보를 전달<br> // First build and send the server handshake packet.<br> serverAuthPluginData, err := c.writeHandshakeV10(l.ServerVersion, l.authServer, uint8(l.charset), l.TLSConfig.Load() != nil)<br> <br> // ...<br><br> // ✅ 클라이언트 응답 수신<br> // 사용자 이름 / 인증 방식 / 암호 응답 값 등 정보를 전달<br> // Wait for the client response. This has to be a direct read,<br> // so we don&#39;t buffer the TLS negotiation packets.<br> response, err := c.readEphemeralPacketDirect()<br> if err != nil {<br>  // Don&#39;t log EOF errors. They cause too much spam, same as main read loop.<br>  if err != io.EOF {<br>   log.Infof(&quot;Cannot read client handshake response from %s: %v, it may not be a valid MySQL client&quot;, c, err)<br>  }<br>  return<br> }<br> user, clientAuthMethod, clientAuthResponse, err := l.parseClientHandshakePacket(c, true, response)<br> if err != nil {<br>  log.Errorf(&quot;Cannot parse client handshake response from %s: %v&quot;, c, err)<br>  return<br> }<br><br> c.recycleReadPacket()<br><br> // ✅ TLS 관련 처리<br> if c.TLSEnabled() {<br>  // ... 여기서는 pass<br> }<br><br> // ✅ 인증 방식 협상<br> // See what auth method the AuthServer wants to use for that user.<br> negotiatedAuthMethod, err := negotiateAuthMethod(c, l.authServer, user, clientAuthMethod)<br><br> // ...<br><br> // ✅ 최증 인증 수행<br> userData, err := negotiatedAuthMethod.HandleAuthPluginData(c, user, serverAuthPluginData, clientAuthResponse, conn.RemoteAddr())<br> // ...<br> <br> // 유저 및 유저 데이터 저장<br> c.User = user<br> c.UserData = userData<br><br> if c.User != &quot;&quot; {<br>  connCountPerUser.Add(c.User, 1)<br>  defer connCountPerUser.Add(c.User, -1)<br> }<br><br> // ✅ 초기 DB 선택<br> // Set initial db name.<br> if c.schemaName != &quot;&quot; {<br>  err = l.handler.ComQuery(c, &quot;use &quot;+sqlescape.EscapeID(c.schemaName), func(result *sqltypes.Result) error {<br>   return nil<br>  })<br>  if err != nil {<br>   c.writeErrorPacketFromError(err)<br>   return<br>  }<br> }<br><br> // ✅ handshake 성공<br> // Negotiation worked, send OK packet.<br> if err := c.writeOKPacket(&amp;PacketOK{statusFlags: c.StatusFlags}); err != nil {<br>  log.Errorf(&quot;Cannot write OK packet to %s: %v&quot;, c, err)<br>  return<br> }<br><br> // ...<br><br> // ✅ connection ready 이벤트 전달<br> l.handler.ConnectionReady(c)<br><br> // ✅ command 루프 진입<br> for {<br>  kontinue := c.handleNextCommand(l.handler)<br>  // before going for next command check if the connection should be closed or not.<br>  if !kontinue || c.IsMarkedForClose() {<br>   return<br>  }<br> }<br>}</pre><p>해당 함수 흐름을 보면 mysql의 연결 과정을 이해할 수 있습니다. 짧게 요약하면 다음과 같습니다.</p><ol><li>커넥션 구조체를 생성합니다.</li><li>Listener의 handler에게 커넥션 생성 이벤트를 전달합니다.</li><li>mysql을 첫 프로토콜 패킷인 핸드셰이크 V10 패킷을 보냅니다.</li><li>서버 V10 패킷에 대한 클라이언트 응답을 확인합니다.</li><li>인증 로직을 수행합니다.</li><li>초기 DB를 선택합니다.</li><li>handshake OK를 보냅니다.</li><li>Listener의 handler에게 ConnectionReady이벤트를 전달합니다.</li><li>커맨드 처리 무한루프를 수행합니다.</li></ol><p>mysql 처리 로직 상에서 중요한 것은 인증보다 내부 로직이니 커맨드 내 무한루프 부분을 확인해보겠습니다. 인증 과정의 세부 로직은 다음 문서에 자세히 설명되어 있습니다.</p><p><a href="https://dev.mysql.com/doc/dev/mysql-server/9.2.0/page_protocol_connection_phase.html">MySQL: Connection Phase</a></p><p>이때 handleNextCommand메서드를 확인할 수 있고 해당 메서드 내부는 다음과 같습니다.</p><pre>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/mysql/conn.go#L890&gt;<br>// handleNextCommand is called in the server loop to process<br>// incoming packets.<br>func (c *Conn) handleNextCommand(handler Handler) bool {<br>	c.sequence = 0<br>	data, err := c.readEphemeralPacket() // ✅ 패킷 Read<br><br>	// ...<br><br>	switch data[0] { // ✅ 맨 앞 데이터 값에 따라 조건 분기<br>	case ComQuit:<br>		c.recycleReadPacket()<br>		return false<br>	case ComInitDB:<br>		db := c.parseComInitDB(data)<br>		c.recycleReadPacket()<br>		res := c.execQuery(&quot;use &quot;+sqlescape.EscapeID(db), handler, false)<br>		return res != connErr<br>	case ComQuery:<br>		return c.handleComQuery(handler, data)<br>	case ComPing:<br>		return c.handleComPing()<br>	case ComSetOption:<br>		return c.handleComSetOption(data)<br>	case ComPrepare:<br>		return c.handleComPrepare(handler, data)<br>	case ComStmtExecute:<br>		return c.handleComStmtExecute(handler, data)<br>	case ComStmtSendLongData:<br>		return c.handleComStmtSendLongData(data)<br>	case ComStmtClose:<br>		stmtID, ok := c.parseComStmtClose(data)<br>		c.recycleReadPacket()<br>		if ok {<br>			delete(c.PrepareData, stmtID)<br>		}<br>	case ComStmtReset:<br>		return c.handleComStmtReset(data)<br>	case ComResetConnection:<br>		c.handleComResetConnection(handler)<br>		return true<br>	case ComFieldList:<br>		c.recycleReadPacket()<br>		if !c.writeErrorAndLog(sqlerror.ERUnknownComError, sqlerror.SSNetError, &quot;command handling not implemented yet: %v&quot;, data[0]) {<br>			return false<br>		}<br>	case ComBinlogDump:<br>		return c.handleComBinlogDump(handler, data)<br>	case ComBinlogDumpGTID:<br>		return c.handleComBinlogDumpGTID(handler, data)<br>	case ComRegisterReplica:<br>		return c.handleComRegisterReplica(handler, data)<br>	default:<br>		log.Errorf(&quot;Got unhandled packet (default) from %s, returning error: %v&quot;, c, data)<br>		c.recycleReadPacket()<br>		if !c.writeErrorAndLog(sqlerror.ERUnknownComError, sqlerror.SSNetError, &quot;command handling not implemented yet: %v&quot;, data[0]) {<br>			return false<br>		}<br>	}<br><br>	return true<br>}</pre><p>해당 로직은 단순합니다.</p><ol><li>패킷을 읽고</li><li>패킷의 첫 자리에 따라 조건을 분기합니다.</li></ol><p>이때 패킷을 읽는 방법에 대하여 확인해봅시다. 그러면 readEphemeralPacket메서드를 확인해야 할 것으로 보입니다.</p><p>해당 메서드의 내부 구현은 다음과 같습니다.</p><pre>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/mysql/conn.go#L420&gt;<br>func (c *Conn) readEphemeralPacket() ([]byte, error) {<br>	// ...<br><br>	// net.Conn<br>	r := c.getReader()<br><br>	// ✅ 패킷 길이 확인<br>	length, err := c.readHeaderFrom(r)<br>	if err != nil {<br>		return nil, err<br>	}<br><br>	c.currentEphemeralPolicy = ephemeralRead<br>	if length == 0 {<br>		// This can be caused by the packet after a packet of<br>		// exactly size MaxPacketSize.<br>		return nil, nil<br>	}<br><br>	// ✅ 일단 MaxPacketSize보다 패킷이 작은 경우만 분석<br>	// Use the bufPool.<br>	if length &lt; MaxPacketSize {<br>		// ✅ 길이만큼 버퍼세팅하고 읽기 진행<br>		c.currentEphemeralBuffer = bufPool.Get(length)<br>		if _, err := io.ReadFull(r, *c.currentEphemeralBuffer); err != nil {<br>			return nil, vterrors.Wrapf(err, &quot;io.ReadFull(packet body of length %v) failed&quot;, length)<br>		}<br>		<br>		// ✅ 읽은 데이터 리턴<br>		return *c.currentEphemeralBuffer, nil<br>	}<br>	<br>	// ...<br><br>	return data, nil<br>}<br><br>// ...<br><br>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/mysql/conn.go#L382&gt;<br>func (c *Conn) readHeaderFrom(r io.Reader) (int, error) {<br><br>	// ...<br><br>	// ✅ 패킷 시퀀스 확인<br>	sequence := uint8(c.header[3])<br>	if sequence != c.sequence {<br>		return 0, vterrors.Errorf(vtrpcpb.Code_INTERNAL, &quot;invalid sequence, expected %v got %v&quot;, c.sequence, sequence)<br>	}<br><br>	c.sequence++<br><br>	// ✅ 패킷 길이 확인<br>	return int(uint32(c.header[0]) | uint32(c.header[1])&lt;&lt;8 | uint32(c.header[2])&lt;&lt;16), nil<br>}</pre><p>readEphemeralPacket 함수의 역할은 단순합니다. 패킷에서 길이를 표현하는 데이터를 읽고, 해당 길이만큼 읽은 데이터를 리턴합니다. 이때 패킷 길이를 추출하는 방법은 readHeaderFrom에 포함되어 있습니다. 이 함수의 구현은 다음 mysql 문서에 나타난 packet과 형식이 같습니다.</p><p><a href="https://dev.mysql.com/doc/dev/mysql-server/9.2.0/page_protocol_basic_packets.html">MySQL: MySQL Packets</a></p><p>패킷을 확인해보면 첫 4바이트가 패킷 헤더로 이루어집니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69xG5YN_Wo7VmjeVt5HpOw.png" /></figure><p>패킷의 구성은 다음과 같습니다:</p><ul><li>3바이트: 패킷의 길이를 나타냅니다.</li><li>1바이트: 패킷의 시퀀스를 나타냅니다.</li><li>나머지: data를 나타냅니다.</li></ul><p>그래서 위의 코드에서 패킷 시퀀스는 sequence := uint8(c.header[3])로, 길이는 int(uint32(c.header[0]) | uint32(c.header[1])&lt;&lt;8 | uint32(c.header[2])&lt;&lt;16)로 확인하고 있습니다.</p><p>이렇게 패킷을 확인하고 다음으로 진행되는 로직은 데이터의 0번 값에 대한 매칭입니다.</p><pre>switch data[0] { // ✅ 맨 앞 데이터 값에 따라 조건 분기<br>	case ComQuit:<br>		c.recycleReadPacket()<br>		return false<br>	case ComInitDB:<br>		db := c.parseComInitDB(data)<br>		c.recycleReadPacket()<br>		res := c.execQuery(&quot;use &quot;+sqlescape.EscapeID(db), handler, false)<br>		return res != connErr<br>	case ComQuery:<br>		return c.handleComQuery(handler, data)<br>	case ComPing:<br>		return c.handleComPing()<br>	case ComSetOption:<br>		return c.handleComSetOption(data)<br>	case ComPrepare:<br>		return c.handleComPrepare(handler, data)<br>	case ComStmtExecute:<br>		return c.handleComStmtExecute(handler, data)<br>	case ComStmtSendLongData:<br>		return c.handleComStmtSendLongData(data)<br>	case ComStmtClose:<br>		stmtID, ok := c.parseComStmtClose(data)<br>		c.recycleReadPacket()<br>		if ok {<br>			delete(c.PrepareData, stmtID)<br>		}<br>	case ComStmtReset:<br>		return c.handleComStmtReset(data)<br>	case ComResetConnection:<br>		c.handleComResetConnection(handler)<br>		return true<br>	case ComFieldList:<br>		c.recycleReadPacket()<br>		if !c.writeErrorAndLog(sqlerror.ERUnknownComError, sqlerror.SSNetError, &quot;command handling not implemented yet: %v&quot;, data[0]) {<br>			return false<br>		}<br>	case ComBinlogDump:<br>		return c.handleComBinlogDump(handler, data)<br>	case ComBinlogDumpGTID:<br>		return c.handleComBinlogDumpGTID(handler, data)<br>	case ComRegisterReplica:<br>		return c.handleComRegisterReplica(handler, data)<br>	default:<br>		log.Errorf(&quot;Got unhandled packet (default) from %s, returning error: %v&quot;, c, data)<br>		c.recycleReadPacket()<br>		if !c.writeErrorAndLog(sqlerror.ERUnknownComError, sqlerror.SSNetError, &quot;command handling not implemented yet: %v&quot;, data[0]) {<br>			return false<br>		}<br>	}</pre><p>해당 매칭 로직은 다음 문서에서 확인할 수 있듯이 여러 종류로 나눠집니다.</p><p><a href="https://dev.mysql.com/doc/dev/mysql-server/9.2.0/page_protocol_command_phase.html">MySQL: Command Phase</a></p><ul><li>text protocol</li><li>utility commands</li><li>prepared statement</li><li>stored programs</li></ul><p>제일 관심있는 부분은 아마 text protocol의 ComQuery일 것입니다. 해당 비트로 시작하는 경우 텍스트 프로토콜 기반 SQL 쿼리를 전달하고 즉시 실행합니다. 이 로직은 handleComQuery메서드 내에 존재합니다.</p><pre>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/mysql/conn.go#L1317&gt;<br>func (c *Conn) handleComQuery(handler Handler, data []byte) (kontinue bool) {<br>	// ...<br>	<br>	// ✅ 쿼리 파싱: 0번을 재외한 모든 데이터<br>	query := c.parseComQuery(data)<br>	c.recycleReadPacket()<br><br>	// ✅ 쿼리가 여러 개로 구분된 경우 처리<br>	var queries []string<br>	var err error<br>	if c.Capabilities&amp;CapabilityClientMultiStatements != 0 {<br>		queries, err = handler.Env().Parser().SplitStatementToPieces(query)<br>		if err != nil {<br>			log.Errorf(&quot;Conn %v: Error splitting query: %v&quot;, c, err)<br>			return c.writeErrorPacketFromErrorAndLog(err)<br>		}<br>	} else {<br>		queries = []string{query}<br>	}<br><br>	// ...<br><br>	for index, sql := range queries {<br>		more := false<br>		if index != len(queries)-1 {<br>			more = true<br>		}<br>		res := c.execQuery(sql, handler, more) // ✅ 쿼리 실행<br>		if res != execSuccess {<br>			return res != connErr<br>		}<br>	}<br><br>	timings.Record(queryTimingKey, queryStart)<br>	return true<br>}<br><br>// 👇 아래 함수 호출<br><br>func (c *Conn) execQuery(query string, handler Handler, more bool) execResult {<br>	callbackCalled := false<br>	// sendFinished is set if the response should just be an OK packet.<br>	sendFinished := false<br><br>	// ✅ 함수 인자로 handler를 주입하고 ComQuery 로직 진행<br>	err := handler.ComQuery(c, query, func(qr *sqltypes.Result) error {<br>		<br>		// ...<br>	<br>	})<br>	<br>	// ...<br><br>	return execSuccess<br>}</pre><p>여기서 handler.ComQuery를 실행하는데 해당 인터페이스의 구현체는 vtgateHandler로 vtgateHandler의 ComQuery를 확인해야 합니다. ✅ 부분 위주로 보면서 함수 스택을 내려가면 됩니다.</p><pre>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/vt/vtgate/plugin_mysql_server.go#L209&gt;<br>func (vh *vtgateHandler) ComQuery(c *mysql.Conn, query string, callback func(*sqltypes.Result) error) error {<br>	session := vh.session(c)<br>	// 세션 상태 체크 및 유저 정보 설정 ...<br>	// ...<br><br>	// OLAP의 경우 스트리밍 방식으로 실행<br>	if session.Options.Workload == querypb.ExecuteOptions_OLAP {<br>		session, err := vh.vtg.StreamExecute(ctx, vh, session, query, make(map[string]*querypb.BindVariable), callback)<br>		if err != nil {<br>			return sqlerror.NewSQLErrorFromError(err)<br>		}<br>		fillInTxStatusFlags(c, session)<br>		return nil<br>	}<br>	<br>	// ✅ 일반 쿼리 실행<br>	session, result, err := vh.vtg.Execute(ctx, vh, session, query, make(map[string]*querypb.BindVariable))<br><br>	if err := sqlerror.NewSQLErrorFromError(err); err != nil {<br>		return err<br>	}<br>	fillInTxStatusFlags(c, session)<br>	return callback(result)<br>}<br><br>// 👇 아래 함수 호출<br><br>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/vt/vtgate/vtgate.go#L463&gt;<br>// Execute executes a non-streaming query.<br>func (vtg *VTGate) Execute(<br>	ctx context.Context, <br>	mysqlCtx vtgateservice.MySQLConnection, <br>	session *vtgatepb.Session, <br>	sql string, <br>	bindVariables map[string]*querypb.BindVariable,<br>) (newSession *vtgatepb.Session, qr *sqltypes.Result, err error) {<br>	<br>	// ...<br><br>	if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {<br>		// ...<br>	} else {<br>		safeSession := NewSafeSession(session)<br>		// ✅ 쿼리 실행<br>		qr, err = vtg.executor.Execute(ctx, mysqlCtx, &quot;Execute&quot;, safeSession, sql, bindVariables)<br>		safeSession.RemoveInternalSavepoint()<br>	}<br>	<br>	// ...<br>	<br>	return session, nil, err<br>}<br><br>// 👇 아래 함수 호출<br><br>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/vt/vtgate/executor.go#L221&gt;<br>func (e *Executor) Execute(<br>	ctx context.Context, <br>	mysqlCtx vtgateservice.MySQLConnection, <br>	method string, <br>	safeSession *SafeSession, <br>	sql string, <br>	bindVars map[string]*querypb.BindVariable,<br>) (result *sqltypes.Result, err error) {<br>	<br>	// ...<br>	<br>	// ✅ 쿼리 실행<br>	stmtType, result, err := e.execute(ctx, mysqlCtx, safeSession, sql, bindVars, logStats)<br>	<br>	// ...<br>}<br><br>// 👇 아래 함수 호출<br><br>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/vt/vtgate/executor.go#L221&gt;<br>func (e *Executor) execute(<br>	ctx context.Context, <br>	mysqlCtx vtgateservice.MySQLConnection, <br>	safeSession *SafeSession, <br>	sql string, <br>	bindVars map[string]*querypb.BindVariable, <br>	logStats *logstats.LogStats,<br>) (sqlparser.StatementType, *sqltypes.Result, error) {<br>	var err error<br>	var qr *sqltypes.Result<br>	var stmtType sqlparser.StatementType<br>	<br>	// ✅ 쿼리 파싱, 분석, 계획, 실행<br>	err = e.newExecute(ctx, mysqlCtx, safeSession, sql, bindVars, logStats, func(ctx context.Context, plan *engine.Plan, vc *vcursorImpl, bindVars map[string]*querypb.BindVariable, time time.Time) error {<br>		stmtType = plan.Type<br>		qr, err = e.executePlan(ctx, safeSession, plan, vc, bindVars, logStats, time)<br>		return err<br>	}, func(typ sqlparser.StatementType, result *sqltypes.Result) error {<br>		stmtType = typ<br>		qr = result<br>		return nil<br>	})<br><br>	return stmtType, qr, err<br>}</pre><p>ComQuery부터 호출 스택을 따라 내려가면 최종으로 execute의 newExecute를 확인할 수 있습니다. 해당 함수에서 쿼리 파싱, 검증, 계획, 실행을 수행합니다. 이 함수는 내용이 길어서 다음 vitess아티클에서 분석해보겠습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab87c95557b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[vitess 분석: vtgate, mysql proxy server를 여는 과정]]></title>
            <link>https://medium.com/@hyper201286/vitess-%EB%B6%84%EC%84%9D-vtgate-mysql-proxy-server%EB%A5%BC-%EC%97%AC%EB%8A%94-%EA%B3%BC%EC%A0%95-bef53103b39e?source=rss-619cbfeff5b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bef53103b39e</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[socket-programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[vites]]></category>
            <dc:creator><![CDATA[flangdu]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 11:43:25 GMT</pubDate>
            <atom:updated>2025-04-04T11:43:25.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_YaqzuycFOLKKzDRkOWZQ.png" /></figure><p>vitess는 mysql을 기반으로 구축된 클라우드 네이티브 수평 확장형 분산 데이터베이스 시스템입니다. 이번 “vitess 분석” 시리즈는 vitess에 대한 동작 원리를 전반적으로 탐색해봅니다. 가장 먼저 확인할 부분은 서버를 열고 vitess에서 커넥션 연결을 대기하는 부분입니다. 이 부분은 vitess 구성 요소 중 vtgate라는 요소가 담당하며 vtgate는 mysql 쿼리를 클라이언트로 받는 프록시 서버 역할을 합니다. 따라서 vtgate를 먼저 분석해보도록 하겠습니다.</p><p>다음 문서를 따라 설치한 환경에서 진행합니다.</p><p><a href="https://vitess.io/docs/21.0/get-started/operator/">Vitess | Vitess Operator for Kubernetes</a></p><p>해당 문서는 vitess의 아키텍처에 대한 어느 정도 이해가 필요합니다.</p><p><a href="https://vitess.io/docs/21.0/overview/architecture/">Vitess | Architecture</a></p><p>go의 net 패키지의 TCP 서버를 간단하게 만들 수 있어야 합니다.</p><p>vitess의 V21.0.3버전에서 시작합니다.</p><p><a href="https://github.com/vitessio/vitess/tree/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f">GitHub — vitessio/vitess at 94fdc736eae8928a8fdde44e9ec9c3bee1868d6f</a></p><h3>vtgate pod의 vitess 진입점 분석</h3><p>vtgate는 vitess 내에서 트래픽을 vttablet 서버로 라우팅하고 통합된 결과를 클라이언트에 다시 반환하는 프록시 서버입니다. mysql 프로토콜을 지원하여 마치 mysql 서버인 것처럼 연결할 수 있습니다. kubernetes에 vitess operator를 배포해보면 vtgate pod가 호스팅 된 것을 확인할 수 있습니다. 아래는 vtgate에 대한 deployment를 출력한 결과물입니다.</p><pre>$ kubectl describe deploy example-zone1-vtgate-bc6cde92 -n vitess-operator<br>Name:                   example-zone1-vtgate-bc6cde92<br>Namespace:              vitess-operator<br>...<br>Pod Template:<br>  Labels:       ...<br>  Containers:<br>   vtgate:<br>    Image:       vitess/lite:v21.0.3<br>    Ports:       15000/TCP, 15999/TCP, 3306/TCP<br>	  ... <br>    Command:<br>      /vt/bin/vtgate<br>    Args:<br>      --buffer_max_failover_duration=10s<br>      --buffer_min_time_between_failovers=20s<br>      --buffer_size=1000<br>      --cell=zone1<br>      --cells_to_watch=zone1<br>      --enable_buffer=true<br>      --grpc_max_message_size=67108864<br>      --grpc_port=15999<br>      --logtostderr=true<br>      --mysql_auth_server_impl=static<br>      --mysql_auth_server_static_file=/vt/secrets/vtgate-static-auth/users.json<br>      --mysql_auth_static_reload_interval=30s<br>      --mysql_server_port=3306<br>      --port=15000<br>      --service_map=grpc-vtgateservice<br>      --tablet_types_to_wait=MASTER,REPLICA<br>      --topo_global_root=/vitess/example/global<br>      --topo_global_server_address=example-etcd-faf13de3-client.vitess-operator.svc:2379<br>      --topo_implementation=etcd2<br>    Limits:<br>      memory:  256Mi<br>    Requests:<br>      cpu:        100m<br>      memory:     256Mi<br>    Liveness:     http-get http://:web/debug/status delay=300s timeout=1s period=10s #success=1 #failure=30<br>    Readiness:    http-get http://:web/debug/health delay=0s timeout=1s period=10s #success=1 #failure=3<br>    Environment:  &lt;none&gt;<br>    Mounts:<br>      /vt/secrets/vtgate-static-auth from vtgate-static-auth-secret (ro)<br>  Volumes:<br>   vtgate-static-auth-secret:<br>    Type:               Secret (a volume populated by a Secret)<br>    SecretName:         example-cluster-config<br>    Optional:           false</pre><p>여기서 확인할 수 있는 정보는 vtgate 실행을 위한 바이너리 호출 정보입니다. vtgate의 바이너리는 /vt/bin/vtgate에 위치하고 Args에 보이는 값을 전달하고 있습니다. 여기서 vtgate는 go의 cobra를 통해 cli형식으로 호출될 것이라는 예상을 해 볼 수 있습니다. 만약 이 가정이 맞다면 좀 더 쉽게 vtgate에 대한 진입점을 찾을 수 있습니다. cobra는 help를 지원하기 때문에 pod 내부에서 help를 입력해보면 될 것입니다.</p><pre>$ kubectl exec -it example-zone1-vtgate-bc6cde92-8589757b5f-rfhjj -n vitess-operator -- /bin/sh<br>$ cd /vt/bin/<br>$ vtgate --help<br>VTGate is a stateless proxy responsible for accepting requests from applications and routing them to the appropriate tablet server(s) for query execution. It speaks both the MySQL Protocol and a gRPC protocol.<br><br>### Key Options<br><br>* `--srv_topo_cache_ttl`: There may be instances where you will need to increase the cached TTL from the default of 1 second to a higher number:<br>        * You may want to increase this option if you see that your topo leader goes down and keeps your queries waiting for a few seconds.</pre><p>다음과 같이 vtgate에 진입하여 help를 입력하면 다음의 프롬프트가 출력되는 것을 확인할 수 있습니다. vtgate의 사용 방법을 안내하고 있습니다. 이제 vitess github 리포지터리를 받아 VTGate is a stateless proxy responsible for accepting requests …를 검색해보면 다음 위치를 찾을 수 있습니다.</p><p>help를 쳤더니 사용 방법을 안내하고 있습니다. VTGate is a stateless proxy responsible for accepting requests문자열을 검색해보면 다음 위치를 찾을 수 있습니다.</p><pre>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/cmd/vtgate/cli/cli.go#L49&gt;<br>var (<br>	// ... <br>	Main = &amp;cobra.Command{<br>		Use:   &quot;vtgate&quot;,<br>		Short: &quot;VTGate is a stateless proxy responsible for accepting requests from applications and routing them to the appropriate tablet server(s) for query execution. It speaks both the MySQL Protocol and a gRPC protocol.&quot;,<br>		Long: `VTGate is a stateless proxy responsible for accepting requests from applications and routing them to the appropriate tablet server(s) for query execution. It speaks both the MySQL Protocol and a gRPC protocol.<br><br>### Key Options<br>` +<br>			&quot;\\n* `--srv_topo_cache_ttl`: There may be instances where you will need to increase the cached TTL from the default of 1 second to a higher number:\\n&quot; +<br>			`	* You may want to increase this option if you see that your topo leader goes down and keeps your queries waiting for a few seconds.`,<br>		Example: `vtgate \\<br>	--topo_implementation etcd2 \\<br>	--topo_global_server_address localhost:2379 \\<br>	--topo_global_root /vitess/global \\<br>	--log_dir $VTDATAROOT/tmp \\<br>	--port 15001 \\<br>	--grpc_port 15991 \\<br>	--mysql_server_port 15306 \\<br>	--cell test \\<br>	--cells_to_watch test \\<br>	--tablet_types_to_wait PRIMARY,REPLICA \\<br>	--service_map &#39;grpc-vtgateservice&#39; \\<br>	--pid_file $VTDATAROOT/tmp/vtgate.pid \\<br>	--mysql_auth_server_impl none`,<br>		Args:    cobra.NoArgs,<br>		Version: servenv.AppVersion.String(),<br>		PreRunE: servenv.CobraPreRunE,<br>		RunE:    run,<br>	}<br>	<br>	// ...<br>)</pre><p>이 Main command의 등록은 다음 위치에서 실행됩니다.</p><pre>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/cmd/vtgate/vtgate.go#L24&gt;<br>func main() {<br>	if err := cli.Main.Execute(); err != nil {<br>		log.Exit(err)<br>	}<br>}</pre><h3>vitess 코드 내부: mysql 프록시 서버 실행</h3><p>지금까지 kubernetes 상에 vitess를 띄우고 어떻게 바이너리를 실행하여 코드 내부 상의 위치를 탐색했습니다. 이번에는 코드 내에서 실제 로직이 호출되는 위치를 파악해보겠습니다.</p><p>Main command가 실행되면 다음이 호출됩니다. Main command의 로직은 토폴로지 서버를 생성하고 vtgate의 초기화를 진행합니다</p><pre>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/cmd/vtgate/cli/cli.go#L141&gt;<br>func run(cmd *cobra.Command, args []string) error {<br>	defer exit.Recover()<br><br>	// ✅ 환경변수 초기화<br>	servenv.Init()<br><br>	// ✅ topology server 초기화(etcd)<br>	// Ensure we open the topo before we start the context, so that the<br>	// defer that closes the topo runs after cancelling the context.<br>	// This ensures that we&#39;ve properly closed things like the watchers<br>	// at that point.<br>	ts := topo.Open()<br>	defer ts.Close()<br><br>	// topo.Server를 기반으로한 resilientServer 생성<br>	resilientServer = srvtopo.NewResilientServer(ctx, ts, srvTopoCounts)<br><br>	// ...<br><br>	// 환경 변수 설정<br>	env, err := vtenv.New(vtenv.Options{<br>		// ...<br>	})<br>	// ...<br><br>	// ✅ vtgate 초기화<br>	// pass nil for HealthCheck and it will be created<br>	vtg := vtgate.Init(ctx, env, nil, resilientServer, cell, tabletTypes, plannerVersion)<br>	<br>	// ...<br>}</pre><p>이 코드는 환경 변수 초기화, topology 서버(ex: etcd) 초기화, vtgate 초기화를 담당합니다. 이 함수에서 가장 중요한 부분은 vtgate.Init입니다. 해당 부분에서 vtgate 패키지의 초기화를 진행합니다. 함수를 다 읽어볼 필요 없이 초기 실행에서는 ✅ 만 확인하면 됩니다.</p><pre>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/vt/vtgate/vtgate.go#L251&gt;<br>func Init(<br>	ctx context.Context,<br>	env *vtenv.Environment,<br>	hc discovery.HealthCheck,<br>	serv srvtopo.Server,<br>	cell string,<br>	tabletTypesToWait []topodatapb.TabletType,<br>	pv plancontext.PlannerVersion,<br>) *VTGate {<br><br>	// TabletGateway 생성<br>	// vttablet 연결 관리 및 헬스 체크<br>	gw := NewTabletGateway(ctx, hc, serv, cell)<br>	gw.RegisterStats()<br>	if err := gw.WaitForTablets(ctx, tabletTypesToWait); err != nil {<br>		log.Fatalf(&quot;tabletGateway.WaitForTablets failed: %v&quot;, err)<br>	}<br><br>	// txConn 생성<br>	// 트랜잭션 상태 관리<br>	tc := NewTxConn(gw, getTxMode())<br>	// 트랜잭션을 지원하는 샤딩 쿼리 실행기(?) 아직 뭔지 모름<br>	// ScatterConn depends on TxConn to perform forced rollbacks.<br>	sc := NewScatterConn(&quot;VttabletCall&quot;, tc, gw)<br>	// 분산 트랜잭션<br>	// TxResolver depends on TxConn to complete distributed transaction.<br>	tr := txresolver.NewTxResolver(gw.hc.Subscribe(), tc)<br>	srvResolver := srvtopo.NewResolver(serv, gw, cell)<br>	// 키스페이스/타입/샤드 분해 및 라우팅<br>	resolver := NewResolver(srvResolver, serv, cell, sc) <br>	// binlog 스트리밍<br>	vsm := newVStreamManager(srvResolver, serv, cell)<br>	<br>	// 토폴로지 서버 초기화<br>	ts, err := serv.GetTopoServer()<br>	<br>	// 스키마 트래커 생성<br>	var st *vtschema.Tracker<br>	if enableSchemaChangeSignal {<br>		st = vtschema.NewTracker(gw.hc.Subscribe(), enableViews, enableUdfs, env.Parser())<br>		addKeyspacesToTracker(ctx, srvResolver, st, gw)<br>		si = st<br>	}<br><br>	// executor 생성: 쿼리 실행 및 분석<br>	executor := NewExecutor(<br>		// ...<br>	)<br>	<br>	// ✅ vtgate 생성<br>	vtgateInst := newVTGate(executor, resolver, vsm, tc, gw)<br>	<br>	// ✅ 서버 실행<br>	servenv.OnRun(func() {<br>		// grpc/mysql 서버 등에 서비스 등록<br>		for _, f := range RegisterVTGates {<br>			f(vtgateInst)<br>		}<br>		// 스키마 트래커 시작<br>		if st != nil &amp;&amp; enableSchemaChangeSignal {<br>			st.Start()<br>		}<br>		// 트랜잭션 리졸버 시작<br>		tr.Start()<br>		// ✅ mysql 서버 시작<br>		srv := initMySQLProtocol(vtgateInst)<br>		if srv != nil {<br>			servenv.OnTermSync(srv.shutdownMysqlProtocolAndDrain)<br>			servenv.OnClose(srv.rollbackAtShutdown)<br>		}<br>	})<br>	<br>	// ...<br>	<br>	return vtgateInst<br>}</pre><p>✅만 확인해보면 해당 함수는 단순하게 서버 생성 및 실행 로직을 담고 있습니다. 간단하게는 다음과 같이 요약할 수 있습니다.</p><ul><li>vtgate를 생성</li><li>서버를 initMySQLProtocol을 호출하여 실행</li></ul><p>그럼 서버 실행하는 부분인 initMySQLProtocol에서 어떤 작업이 일어나는지 살펴보겠습니다. 이 함수는 vtgate를 mysql 서버처럼 보이게 만드는 TCP/socket 리스너 초기화 함수입니다.</p><pre>// &lt;https://github.com/vitessio/vitess/blob/94fdc736eae8928a8fdde44e9ec9c3bee1868d6f/go/vt/vtgate/plugin_mysql_server.go#L492&gt;<br>// initMySQLProtocol starts the mysql protocol.<br>// It should be called only once in a process.<br>func initMySQLProtocol(vtgate *VTGate) *mysqlServer {<br>	// ...<br><br>	// ✅ TCP 리스너 생성<br>	// Create a Listener.<br>	var err error<br>	srv := &amp;mysqlServer{}<br>	srv.vtgateHandle = newVtgateHandler(vtgate) // ✅ 연결 핸들러 생성: 커넥션 이벤트 발생 시 핸들러 이벤트 호출<br>	if mysqlServerPort &gt;= 0 {<br>		srv.tcpListener, err = mysql.NewListener( // ✅ TCP 서버 생성<br>			// ...<br>		)<br>		<br>		// ...<br>		<br>		// Start listening for tcp<br>		// ✅ TCP 서버 실행<br>		go srv.tcpListener.Accept()<br>	}<br>	<br>	// ...<br>}</pre><p>해당 함수의 역할은 몇 가지가 더 있지만, 현재 관심있는 부분은 TCP 서버를 여는 부분입니다. 해당 관점으로 살펴보면 이 함수의 역할은 단순하게 요약할 수 있습니다.</p><ul><li>TCP 연결 핸들러를 생성하고</li><li>mysql.NewListener로 TCP 서버 생성하고</li><li>goroutine으로 tcpListener.Accept을 호출합니다.</li></ul><p>서버가 어떤 형태로 생성되는지 확인하고 싶다면 mysql.NewListener메서드를 확인하면 됩니다. 이 함수 내부를 확인해보면 어떻게 TCP 서버를 생성하고 있는지 확인할 수 있습니다.</p><pre>// &lt;https://github.com/vitessio/vitess/blob/b0352bd57c9fba3c4c1fb94f1ed59d5c7e54bf6d/go/mysql/server.go#L252&gt;<br>// NewListener creates a new Listener.<br>func NewListener(<br>	protocol, address string,<br>	authServer AuthServer,<br>	handler Handler,<br>	connReadTimeout time.Duration,<br>	connWriteTimeout time.Duration,<br>	proxyProtocol bool,<br>	connBufferPooling bool,<br>	keepAlivePeriod time.Duration,<br>	flushDelay time.Duration,<br>) (*Listener, error) {<br>	// ✅ net.Listen을 이용하여 golang 기본 net 패키지로 TCP 서버를 호스팅<br>	listener, err := net.Listen(protocol, address)<br>	if err != nil {<br>		return nil, err<br>	}<br>	<br>	// ...<br><br>	return NewFromListener(listener, authServer, handler, connReadTimeout, connWriteTimeout, connBufferPooling, keepAlivePeriod, flushDelay)<br>}</pre><p>여기서 net.Listen을 호출하여 go의 기본적인 net 패키지를 활용하여 tcp 서버를 만든다는 것을 알 수 있습니다. 이렇게 go의 기본 라이브러리를 활용하여 Listener를 반환합니다. 이렇게 Listener를 생성하고 소켓 생성 이벤트와 여러 설정을 부여합니다. 다음은 Listener.Accept을 확인해보겠습니다. Listener.Accept은 TCP 서버에 연결된 커넥션을 확인하고 각 커넥션마다 goroutine을 할당하는 역할을 수행합니다.</p><pre>// &lt;https://github.com/vitessio/vitess/blob/b0352bd57c9fba3c4c1fb94f1ed59d5c7e54bf6d/go/mysql/server.go#L328&gt;<br>// Accept runs an accept loop until the listener is closed.<br>func (l *Listener) Accept() {<br>	ctx := context.Background()<br><br>	for {<br>		// ✅ 커넥션 연결 블로킹<br>		conn, err := l.listener.Accept()<br>		if err != nil { // error가 nil인 경우 Close() 명시 호출로 간주<br>			// Close() was probably called.<br>			connRefuse.Add(1)<br>			return<br>		}<br><br>		acceptTime := time.Now()<br><br>		connectionID := l.connectionID<br>		l.connectionID++<br><br>		// ✅ 커넥션 개수 기록<br>		connCount.Add(1)<br>		connAccept.Add(1)<br><br>		go func() {<br>			// ...<br>			<br>			// ✅ 실제 로직 함수 handle 호출<br>			l.handle(conn, connectionID, acceptTime)<br>		}()<br>	}<br>}</pre><p>해당 함수 내부에서 net.Listener의 Accept을 호출하여 블로킹으로 소켓 연결을 대기하고 있습니다. 커넥션 연결이 수락됐다면 연결 수락 시간을 기록한 후, 커넥션 아이디를 기록하고 소켓에 대한 핸들함수인 l.handle을 각 소켓마다 goroutine으로 실행합니다. 여기서 클라이언트의 연결이 N개이면, 실행되는 클라이언트 연결에 대한 goroutine도 N개라는 것을 알 수 있습니다. 또한 코드를 확인했을 때 mysql 서버에 쿼리를 처리하는 부분은 l.handle함수 내부에 존재한다는 것을 알 수있습니다.</p><p>다음 아티클은 l.handle함수 내부를 살펴보고 연결된 소켓이 어떻게 처리되는지 확인해보겠습니다.</p><p>참고자료</p><p><a href="https://vitess.io/docs/archive/19.0/concepts/vtgate/">Vitess | VTGate</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bef53103b39e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[argocd 분석: argocd가 다른 클러스터를 모니터링하는 방법: LiveStateCache]]></title>
            <link>https://medium.com/@hyper201286/argocd-%EB%B6%84%EC%84%9D-argocd%EA%B0%80-%EB%8B%A4%EB%A5%B8-%ED%81%B4%EB%9F%AC%EC%8A%A4%ED%84%B0%EB%A5%BC-%EB%AA%A8%EB%8B%88%ED%84%B0%EB%A7%81%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95-livestatecache-6caca9ac75b3?source=rss-619cbfeff5b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6caca9ac75b3</guid>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[argo-cd]]></category>
            <dc:creator><![CDATA[flangdu]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 02:40:47 GMT</pubDate>
            <atom:updated>2025-03-22T02:46:25.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*bO3GF_tJsJAM1--dUqiJmw.png" /></figure><p>저번에는 gitops-engine 내부에서 어떻게 대상 클러스터에 배포된 애플리케이션 상태를 모니터링하는지 살펴봤습니다. gitops-engine 내부에서 ClusterCache를 이용하여 대상 클러스터의 오브젝트 타입을 디스커버리하고 클러스터 리소스 변화를 감지했을 때 이벤트를 발생시키는 방식으로 동작한다는 것을 이해했습니다. 이번에는 ClusterCache가 argocd와 어떻게 상호작용하는지 알아보겠습니다.</p><h3>liveStateCache의 클러스터 조회</h3><p>argocd는 LiveStateCache라는 인터페이스로 클러스터에 대한 정보를 조회하고 있습니다. 이 인터페이스의 실제 구현체는 liveStateCache가 수행하고 있습니다. 인터페이스와 구조체의 필드를 각각 살펴보면 다음과 같습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/cache/cache.go#L119&gt;<br>type LiveStateCache interface {<br>	// Returns k8s server version<br>	GetVersionsInfo(serverURL string) (string, []kube.APIResourceInfo, error)<br>	// Returns true of given group kind is a namespaced resource<br>	IsNamespaced(server string, gk schema.GroupKind) (bool, error)<br>	// Returns synced cluster cache<br>	GetClusterCache(server string) (clustercache.ClusterCache, error)<br>	// Executes give callback against resource specified by the key and all its children<br>	IterateHierarchy(server string, key kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error<br>	// Executes give callback against resources specified by the keys and all its children<br>	IterateHierarchyV2(server string, keys []kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error<br>	// Returns state of live nodes which correspond for target nodes of specified application.<br>	GetManagedLiveObjs(a *appv1.Application, targetObjs []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error)<br>	// IterateResources iterates all resource stored in cache<br>	IterateResources(server string, callback func(res *clustercache.Resource, info *ResourceInfo)) error<br>	// Returns all top level resources (resources without owner references) of a specified namespace<br>	GetNamespaceTopLevelResources(server string, namespace string) (map[kube.ResourceKey]appv1.ResourceNode, error)<br>	// Starts watching resources of each controlled cluster.<br>	Run(ctx context.Context) error<br>	// Returns information about monitored clusters<br>	GetClustersInfo() []clustercache.ClusterInfo<br>	// Init must be executed before cache can be used<br>	Init() error<br>}<br><br>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/cache/cache.go#L208&gt;<br>type liveStateCache struct {<br>	db                   db.ArgoDB<br>	appInformer          cache.SharedIndexInformer<br>	onObjectUpdated      ObjectUpdatedHandler<br>	kubectl              kube.Kubectl<br>	settingsMgr          *settings.SettingsManager<br>	metricsServer        *metrics.MetricsServer<br>	clusterSharding      sharding.ClusterShardingCache<br>	resourceTracking     argo.ResourceTracking<br>	ignoreNormalizerOpts normalizers.IgnoreNormalizerOpts<br><br>	clusters      map[string]clustercache.ClusterCache<br>	cacheSettings cacheSettings<br>	lock          sync.RWMutex<br>}</pre><p>여기서 liveStateCache 구조체의 clusters라는 필드에서 이전에 분석한 gitops-engine의 clustercache.ClusterCache를 맵 형태로 가지고 있습니다.</p><p>liveStateCache는 getCluster라는 메서드가 존재하는데 여기서 ClusterCache를 생성하고 clusters 필드에 저장합니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/cache/cache.go#L457&gt;<br>func (c *liveStateCache) getCluster(server string) (clustercache.ClusterCache, error) {<br><br>	// ...<br>	<br>	clusterCache, ok = c.clusters[server]<br>	if ok {<br>		return clusterCache, nil<br>	}<br>	<br>	// cluster config &amp; 옵션 생성<br>	clusterCacheConfig, err := cluster.RESTConfig()<br>	<br>	clusterCacheOpts := []clustercache.UpdateSettingsFunc{ // ...<br>	}<br>	<br>	// ✅ clusterCache 생성<br>	clusterCache = clustercache.NewClusterCache(clusterCacheConfig, clusterCacheOpts...)<br>	<br>	// ✅ 리소스 업데이트 함수 등록<br>	_ = clusterCache.OnResourceUpdated(func(newRes *clustercache.Resource, oldRes *clustercache.Resource, namespaceResources map[kube.ResourceKey]*clustercache.Resource) { // ...<br>	}<br>	<br>	// ✅ 업데이트 함수 등록<br>	_ = clusterCache.OnEvent(func(event watch.EventType, un *unstructured.Unstructured) { // ...<br>	}<br>	<br>	// ...<br>	<br>	// ✅ 클러스터 등록<br>	c.clusters[server] = clusterCache<br><br>	return clusterCache, nil<br>}</pre><p>메서드의 역할을 살펴보면 server 이름이 들어오면 clusters에서 조회합니다. 조회되면 early return하고 조회되지 않으면 클러스터를 생성하고 gitops-engine의 ClusterCache에 이벤트를 등록합니다.</p><p>getCluster메서드는 private이기 때문에 어느 상위 함수로부터 호출됩니다. 이 함수는 getSyncedCluster라는 메서드로 한 번 더 감싸지게 됩니다. 이 함수를 살펴보면 다음과 같습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/cache/cache.go#L613&gt;<br>func (c *liveStateCache) getSyncedCluster(server string) (clustercache.ClusterCache, error) {<br>	clusterCache, err := c.getCluster(server)<br>	if err != nil {<br>		return nil, fmt.Errorf(&quot;error getting cluster: %w&quot;, err)<br>	}<br>	err = clusterCache.EnsureSynced()<br>	if err != nil {<br>		return nil, fmt.Errorf(&quot;error synchronizing cache state : %w&quot;, err)<br>	}<br>	return clusterCache, nil<br>}</pre><p>getSyncedCluster는 ClusterCache를 가져와서 EnsureSynced를 호출합니다. 그러면 이 함수가 호출되는 시점에 argocd는 다른 클러스터에 대한 현재 상태를 확인할 수 있습니다. 이 메서드는 liveStateCache의 다른 여러 public 메서드에서 호출됩니다. 아래 함수는 내부에서 위의 getSyncedCluster를 호출하는 함수입니다.</p><pre>func (c *liveStateCache) IsNamespaced(server string, gk schema.GroupKind) (bool, error)<br>func (c *liveStateCache) IterateHierarchy(server string, key kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error<br>func (c *liveStateCache) IterateHierarchyV2(server string, keys []kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error<br>func (c *liveStateCache) IterateResources(server string, callback func(res *clustercache.Resource, info *ResourceInfo)) error<br>func (c *liveStateCache) GetNamespaceTopLevelResources(server string, namespace string) (map[kube.ResourceKey]appv1.ResourceNode, error)<br>func (c *liveStateCache) GetManagedLiveObjs(a *appv1.Application, targetObjs []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error)<br>func (c *liveStateCache) GetVersionsInfo(serverURL string) (string, []kube.APIResourceInfo, error)</pre><p>예를 들어 IsNamespaced는 appStateManager의 CompareAppState에서 호출됩니다. 또한 IterateHierachyV2, GetNamespaceTopLevelResources는 ApplicationController의 getResourceTree에서 호출합니다. 이처럼 getSyncedCluster는 여러 부분에서 호출되지만 대략적으로 ApplicationController 수준에서 리소스를 가져올 때 호출됨을 알 수 있습니다.</p><h3>liveStateCache의 이벤트 처리</h3><p>이번에는 liveStateCache에서 어떻게 이 이벤트를 처리하는지 확인해보겠습니다. 이를 확인하기 위해 다시 getCluster 메서드를 살펴보겠습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/cache/cache.go#L457&gt;<br>func (c *liveStateCache) getCluster(server string) (clustercache.ClusterCache, error) {<br><br>	// ...<br>	<br>		_ = clusterCache.OnResourceUpdated(func(newRes *clustercache.Resource, oldRes *clustercache.Resource, namespaceResources map[kube.ResourceKey]*clustercache.Resource) {<br>		toNotify := make(map[string]bool)<br>		var ref v1.ObjectReference // 변경된 리소스 정보 저장<br>		if newRes != nil {<br>			ref = newRes.Ref<br>		} else {<br>			ref = oldRes.Ref<br>		}<br><br>		c.lock.RLock()<br>		cacheSettings := c.cacheSettings<br>		c.lock.RUnlock()<br><br>		// 불필요한 업데이트 무시: 이전 / 이후 리소스가 모두 존재할 때 skipResourceUpdate가 참이면 무시<br>		if cacheSettings.ignoreResourceUpdatesEnabled &amp;&amp; oldRes != nil &amp;&amp; newRes != nil &amp;&amp; skipResourceUpdate(resInfo(oldRes), resInfo(newRes)) {<br>			// Additional check for debug level so we don&#39;t need to evaluate the<br>			// format string in case of non-debug scenarios<br>			if log.GetLevel() &gt;= log.DebugLevel {<br>				namespace := ref.Namespace<br>				if ref.Namespace == &quot;&quot; {<br>					namespace = &quot;(cluster-scoped)&quot;<br>				}<br>				log.WithFields(log.Fields{<br>					&quot;server&quot;:      cluster.Server,<br>					&quot;namespace&quot;:   namespace,<br>					&quot;name&quot;:        ref.Name,<br>					&quot;api-version&quot;: ref.APIVersion,<br>					&quot;kind&quot;:        ref.Kind,<br>				}).Debug(&quot;Ignoring change of object because none of the watched resource fields have changed&quot;)<br>			}<br>			return<br>		}<br><br>		<br>		for _, r := range []*clustercache.Resource{newRes, oldRes} {<br>			if r == nil {<br>				continue<br>			}<br>			// ✅ 리소스에 대한 app을 가져옴<br>			app := getApp(r, namespaceResources)<br>			if app == &quot;&quot; || skipAppRequeuing(r.ResourceKey()) {<br>				continue<br>			}<br>			// ✅ toNotify에 application 등록: toNotify는 크기가 거의 1<br>			toNotify[app] = isRootAppNode(r) || toNotify[app]<br>		}<br>		// ✅ liveStateCache의 onObjectUpdated 호출<br>		c.onObjectUpdated(toNotify, ref)<br>	})<br>	<br>	// OnEvent 에는 별로 특별한 이벤트가 발생하지 않음<br>	_ = clusterCache.OnEvent(func(event watch.EventType, un *unstructured.Unstructured) {<br>		gvk := un.GroupVersionKind()<br>		c.metricsServer.IncClusterEventsCount(cluster.Server, gvk.Group, gvk.Kind)<br>	})<br><br>	// ...<br><br>}</pre><p>getCluster 내부에서 ClusterCache의 OnResourceUpdated와 OnEvent를 호출하여 이벤트 등록하는 과정이 존재합니다. OnEvent는 간단한 함수이기 때문에 OnResourceUpdated만 확인해보겠습니다.</p><p>내부 로직은</p><ul><li>불필요한 리소스는 무시</li><li>변화한 리소스에 대한 app을 가져옴</li><li>toNotify에 application 등록</li><li>liveStateCache의 onObjectUpdated 호출</li></ul><p>순서로 호출됩니다. 그럼 살펴봐야 할 것은 liveStateCache의 onObjectUpdated 메서드입니다.</p><p>그럼 onObjectUpdated는 어디서 오는지 찾아보겠습니다. 이 정보는 NewLiveStateCache에서 찾을 수 있습니다.</p><pre>func NewLiveStateCache(<br>	db db.ArgoDB,<br>	appInformer cache.SharedIndexInformer,<br>	settingsMgr *settings.SettingsManager,<br>	kubectl kube.Kubectl,<br>	metricsServer *metrics.MetricsServer,<br>	onObjectUpdated ObjectUpdatedHandler, // ✅ 이 부분에서 핸들러 등록<br>	clusterSharding sharding.ClusterShardingCache,<br>	resourceTracking argo.ResourceTracking,<br>) LiveStateCache {<br>	return &amp;liveStateCache{<br>		appInformer:      appInformer,<br>		db:               db,<br>		clusters:         make(map[string]clustercache.ClusterCache),<br>		onObjectUpdated:  onObjectUpdated, // ✅ 이 부분에서 핸들러 등록<br>		kubectl:          kubectl,<br>		settingsMgr:      settingsMgr,<br>		metricsServer:    metricsServer,<br>		clusterSharding:  clusterSharding,<br>		resourceTracking: resourceTracking,<br>	}<br>}</pre><p>이제 LiveClusterCache의 생성자가 어디서 호출되는지 찾아야 합니다. 생성자가 호출되는 위치는 ApplicationController가 생성되는 부분에서 확인할 수 있습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/appcontroller.go#L151&gt;<br>// NewApplicationController creates new instance of ApplicationController.<br>func NewApplicationController(<br>	// ...<br>) (*ApplicationController, error) {<br>	<br>	// ...<br>	<br>	ctrl := ApplicationController{<br>		// ...<br>	}<br>	<br>	// ...<br><br>	// ✅ NewLiveStateCache에 ctrl.handleObjectUpdated를 등록<br>	stateCache := statecache.NewLiveStateCache(db, appInformer, ctrl.settingsMgr, kubectl, ctrl.metricsServer, ctrl.handleObjectUpdated, clusterSharding, argo.NewResourceTracking())<br>	<br>	// ... controller에 stateCache등록<br>	<br>	return &amp;ctrl, nil<br>}</pre><p>이때 주입되는 handleObjectUpdated를 확인해보면 다음과 같습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/appcontroller.go#L397&gt;<br>func (ctrl *ApplicationController) handleObjectUpdated(managedByApp map[string]bool, ref v1.ObjectReference) {<br>	// ✅ managedByApp은 크기가 대부분의 경우에 1<br>	// 만약 이것보다 크다면 하나의 리소스 업데이트가 두 개의 app에 영향을 준다는 의미<br>	<br>	// ...<br>	<br>	for appName, isManagedResource := range managedByApp {<br>		// The appName is given as &lt;namespace&gt;_&lt;name&gt;, but the indexer needs it<br>		// format &lt;namespace&gt;/&lt;name&gt;<br>		appKey := ctrl.toAppKey(appName)<br>		obj, exists, err := ctrl.appInformer.GetIndexer().GetByKey(appKey)<br>		app, ok := obj.(*appv1.Application) //  ✅ app 가져오기<br>		if exists &amp;&amp; err == nil &amp;&amp; ok &amp;&amp; isSelfReferencedApp(app, ref) {<br>			// Don&#39;t force refresh app if related resource is application itself. This prevents infinite reconciliation loop.<br>			continue<br>		}<br><br>		// ...<br><br>		// ✅ refreshQueue에 추가하고 후에 refresh 함수 호출<br>		ctrl.requestAppRefresh(app.QualifiedName(), &amp;level, nil)<br>	}<br>}</pre><p>로직을 간단히 살펴보면 변화한 app과 변화한 k8s 오브젝트가 인자로 들어오고 app을 requestAppRefresh를 호출하여 app 새로 고침 이벤트를 발행합니다. 그럼 requestAppRefresh를 실행하는 큐에서 이벤트를 감지하고 오브젝트를 재갱신합니다.</p><p>그럼 이제 argocd가 어떻게 다른 클러스터의 이벤트를 감지하는지 알 수 있습니다.</p><ol><li>ApplicationController가 생성될 때 LiveClusterCache가 생성되고 이벤트가 등록됨</li><li>ApplicationController에서 클러스터에 대한 리소스 조회가 발생할 때 LiveClusterCache의 getCluster를 호출하고 클러스터 별로 최초 호출 시 LiveClusterCache는 gitops-engine의 ClusterCache를 생성</li><li>생성된 ClusterCache의 EnsureSynced를 호출하면 모든 클러스터 타입에 대한 Watcher가 동작하게 되고 이벤트 감시를 시작</li><li>이벤트가 감지되면 등록된 이벤트 핸들러를 호출: 상위 레이어로 이벤트가 전달되면서 ApplicationController의 requestAppRefresh가 호출됨</li></ol><pre>sequenceDiagram<br>    participant ApplicationController<br>    participant LiveClusterCache<br>    participant ClusterCache<br>    participant Watcher<br><br>    ApplicationController-&gt;&gt;LiveClusterCache: 생성 시 LiveClusterCache 생성 및 이벤트 등록<br>    ApplicationController-&gt;&gt;LiveClusterCache: 클러스터 리소스 조회<br>    LiveClusterCache-&gt;&gt;LiveClusterCache: getSyncedCluster 호출<br>    LiveClusterCache-&gt;&gt;LiveClusterCache: getCluster 호출<br>    LiveClusterCache-&gt;&gt;ClusterCache: ClusterCache 생성 (클러스터 별 최초 호출 시)<br>    ClusterCache-&gt;&gt;ClusterCache: EnsureSynced 호출<br>    ClusterCache-&gt;&gt;Watcher: 모든 클러스터 타입에 대한 Watcher 동작 시작<br>    Watcher--&gt;&gt;ClusterCache: 이벤트 감지<br>    ClusterCache--&gt;&gt;LiveClusterCache: 등록된 이벤트 핸들러 호출<br>    LiveClusterCache--&gt;&gt;ApplicationController: requestAppRefresh 호출</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*JG-b4IM0dZnCfI-lbPogRw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6caca9ac75b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[argocd 분석: argocd가 다른 클러스터를 모니터링하는 방법: ClusterCache]]></title>
            <link>https://medium.com/@hyper201286/argocd-%EB%B6%84%EC%84%9D-argocd%EA%B0%80-%EB%8B%A4%EB%A5%B8-%ED%81%B4%EB%9F%AC%EC%8A%A4%ED%84%B0%EB%A5%BC-%EB%AA%A8%EB%8B%88%ED%84%B0%EB%A7%81%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95-clustercache-2315d9edd741?source=rss-619cbfeff5b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2315d9edd741</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[flangdu]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 13:59:05 GMT</pubDate>
            <atom:updated>2025-03-16T13:59:05.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*bO3GF_tJsJAM1--dUqiJmw.png" /></figure><p>argocd는 다른 클러스터에 배포한 애플리케이션의 상태를 모니터링 할 수 있습니다. 그럼 argocd는 다른 클러스터의 리소스를 어떻게 확인하는 걸까요? argocd 내부에서 어떻게 이 로직이 동작하는지 확인해보겠습니다.</p><h3>DiscoveryClient</h3><p>argocd가 다른 클러스터의 리소스를 어떻게 감시하는지 이해하기 위해 먼저 kubernetes/client-go의 DiscoveryClient에 대해 알아보겠습니다.</p><p>kubernetes에는 여러 오브젝트가 존재합니다. pod, deployment, service와 같은 기본적인 오브젝트일 수 있고 다른 operator가 관리하는 커스텀 리소스일 수 있습니다. 각 클러스터는 서로 다른 오브젝트 타입을 소유합니다. 따라서 kubernetes 리소스를 감시하려면 가장 먼저 해야 하는 작업은 현재 대상 클러스터가 어떤 오브젝트 타입을 소유하는지 아는 것입니다. 이를 알기 위해 kubernetes/client-go의 DiscoveryClient를 활용합니다.</p><p>아래 코드는 DiscoveryClient를 이용하여 대상 클러스터에 존재하는 모든 리소스 타입을 출력하는 예시입니다. kubectl을 사용할 수 있는 로컬 환경이나 pod 내부에서 사용할 수 있습니다.</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;os&quot;<br><br>	&quot;github.com/rs/zerolog/log&quot;<br>	metav1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;<br>	&quot;k8s.io/apimachinery/pkg/runtime/schema&quot;<br>	&quot;k8s.io/client-go/discovery&quot;<br>	&quot;k8s.io/client-go/rest&quot;<br>	&quot;k8s.io/client-go/tools/clientcmd&quot;<br>)<br><br>func main() {<br>	config, err := getKubeConfig()<br>	if err != nil {<br>		log.Fatal().Err(err).Send()<br>	}<br><br>	// ✅ discovery client 생성: api server에서 지원하는 리소스를 검색<br>	disco, err := discovery.NewDiscoveryClientForConfig(config)<br>	if err != nil {<br>		log.Fatal().Err(err).Send()<br>	}<br><br>	// ✅ cluster version 조회<br>	version, err := disco.ServerVersion()<br>	if err != nil {<br>		log.Fatal().Err(err).Send()<br>	}<br><br>	// ✅ server resources 조회<br>	_, serverResources, err := disco.ServerGroupsAndResources()<br>	if err != nil {<br>		log.Fatal().Err(err).Send()<br>	}<br><br>	// ✅ version 출력<br>	fmt.Printf(&quot;%s.%s\\n&quot;, version.Major, version.Minor)<br><br>	// ✅ cluster에 존재하는 모든 리소스 타입 순회<br>	// ✅ 첫번째 루프는 group version(ex: &quot;argoproj.io/v1alpha1&quot;)<br>	for _, apiResourceList := range serverResources {<br>		gv, err := schema.ParseGroupVersion(apiResourceList.GroupVersion)<br>		if err != nil {<br>			log.Fatal().Err(err).Send()<br>		}<br>		// ✅ 두번째 루프는 APIResource(ex: &quot;applications&quot;, &quot;applicationsets&quot;)<br>		for _, apiResource := range apiResourceList.APIResources {<br>			fmt.Printf(&quot;group %s \\t kind %s \\t name %s\\n&quot;, gv.Group, apiResource.Kind, apiResource.Name)<br>		}<br>	}<br>}<br><br>func getKubeConfig() (*rest.Config, error) {<br>	config, err := rest.InClusterConfig()<br>	if err == nil {<br>		return config, nil<br>	}<br><br>	kubeconfig := os.ExpandEnv(&quot;$HOME/.kube/config&quot;) // 환경 변수 값 대체<br>	return clientcmd.BuildConfigFromFlags(&quot;&quot;, kubeconfig)<br>}</pre><p>실행 예시 결과입니다.</p><pre>$ go run .<br>// 1.32<br>// group security.istio.io 	 kind AuthorizationPolicy 	 name authorizationpolicies<br>// group security.istio.io 	 kind AuthorizationPolicy 	 name authorizationpolicies/status<br>// group security.istio.io 	 kind PeerAuthentication 	 name peerauthentications<br>// group security.istio.io 	 kind PeerAuthentication 	 name peerauthentications/status<br>// group security.istio.io 	 kind RequestAuthentication 	 name requestauthentications<br>// group security.istio.io 	 kind RequestAuthentication 	 name requestauthentications/status<br>// ...</pre><p>kubernetes의 *rest.Config를 가져와서 discovery.NewDiscoveryClientForConfig를 호출하면 DiscoveryClient를 얻습니다. 이 클라이언트를 이용하면 kubernetes의 서버 버전과 클러스터 내부에 존재하는 오브젝트 타입을 찾을 수 있습니다. 위의 예시 구현에서 version, err := disco.ServerVersion()을 이용하여 서버 버전을 탐색고 _, serverResources, err := disco.ServerGroupsAndResources()을 이용하여 클러스터 내부의 리소스 타입을 탐색했습니다. argocd 내부의 gitops-engine은 이 DynamicClient를 활용하여 다른 클러스터의 오브젝트 타입을 동적으로 탐색합니다.</p><h3>gitops-engine 내부의 kubectl 구현체</h3><p>gitops-engine에는 내부에서 kubectl 구현체를 만들어 DynamicClient를 추상화하여 동적으로 다른 클러스터의 리소스 타입을 찾는 로직을 구현하고 있습니다. kubectl을 추상화한 코드에서 어떻게 argocd는 DynamicClient를 사용하는지 살펴보겠습니다.</p><p>먼저 DynamicClient는 KubectlCmd라는 구조체에서 활용됩니다. 구조체 정의는 아래에서 확인할 수 있습니다. KubectlCmd는 Kubectl인터페이스를 구현합니다.</p><pre>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/utils/kube/ctl.go#L30&gt;<br><br>type Kubectl interface {<br>	ManageResources(config *rest.Config, openAPISchema openapi.Resources) (ResourceOperations, func(), error)<br>	LoadOpenAPISchema(config *rest.Config) (openapi.Resources, *managedfields.GvkParser, error)<br>	ConvertToVersion(obj *unstructured.Unstructured, group, version string) (*unstructured.Unstructured, error)<br>	DeleteResource(ctx context.Context, config *rest.Config, gvk schema.GroupVersionKind, name string, namespace string, deleteOptions metav1.DeleteOptions) error<br>	GetResource(ctx context.Context, config *rest.Config, gvk schema.GroupVersionKind, name string, namespace string) (*unstructured.Unstructured, error)<br>	CreateResource(ctx context.Context, config *rest.Config, gvk schema.GroupVersionKind, name string, namespace string, obj *unstructured.Unstructured, createOptions metav1.CreateOptions, subresources ...string) (*unstructured.Unstructured, error)<br>	PatchResource(ctx context.Context, config *rest.Config, gvk schema.GroupVersionKind, name string, namespace string, patchType types.PatchType, patchBytes []byte, subresources ...string) (*unstructured.Unstructured, error)<br>	GetAPIResources(config *rest.Config, preferred bool, resourceFilter ResourceFilter) ([]APIResourceInfo, error)<br>	GetServerVersion(config *rest.Config) (string, error)<br>	NewDynamicClient(config *rest.Config) (dynamic.Interface, error)<br>	SetOnKubectlRun(onKubectlRun OnKubectlRunFunc)<br>}<br><br>type KubectlCmd struct {<br>	Log          logr.Logger<br>	Tracer       tracing.Tracer<br>	OnKubectlRun OnKubectlRunFunc<br>}</pre><p>직접 KubectlCmd가 dynamicClient를 내부 필드로 소유하진 않지만 여러 메서드에서 DynamicClient를 활용하는 것을 확인할 수 있습니다. kubernetes 버전을 가져오는 명령어인 GetServerVersion와 리소스 타입을 가져오는 명령어인 GetAPIResources을 살펴보겠습니다.</p><p><strong>GetServerVersion</strong></p><pre>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/utils/kube/ctl.go#L312&gt;<br>func (k *KubectlCmd) GetServerVersion(config *rest.Config) (string, error) {<br>	// ...<br>	// ✅ discovery 클라이언트 생성하여 ServerVersion 조회<br>	client, err := discovery.NewDiscoveryClientForConfig(config)<br>	// ...<br>	v, err := client.ServerVersion()<br>	// ...<br>	return fmt.Sprintf(&quot;%s.%s&quot;, v.Major, v.Minor), nil<br>}</pre><p><strong>GetAPIResources</strong></p><pre>// https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/utils/kube/ctl.go#L165<br>func (k *KubectlCmd) GetAPIResources(config *rest.Config, preferred bool, resourceFilter ResourceFilter) ([]APIResourceInfo, error) {<br> // ...<br> // ✅ filterAPIResources 호출<br> apiResIfs, err := k.filterAPIResources(config, preferred, resourceFilter, func(apiResource *metav1.APIResource) bool {<br>  return isSupportedVerb(apiResource, listVerb) &amp;&amp; isSupportedVerb(apiResource, watchVerb)<br> })<br> // ...<br>}<br><br>// https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/utils/kube/ctl.go#L58<br>func (k *KubectlCmd) filterAPIResources(config *rest.Config, preferred bool, resourceFilter ResourceFilter, filter filterFunc) ([]APIResourceInfo, error) {<br> // ✅ DiscoveryClient 생성<br> disco, err := discovery.NewDiscoveryClientForConfig(config)<br><br> // ✅ 클러스터에 존재하는 리소스 조회<br> var serverResources []*metav1.APIResourceList<br> if preferred {<br>  serverResources, err = disco.ServerPreferredResources()<br> } else {<br>  _, serverResources, err = disco.ServerGroupsAndResources()<br> }<br><br> // ✅ cluster에 존재하는 모든 리소스 타입 순회<br> // ✅ 첫번째 루프는 group version(ex: &quot;argoproj.io/v1alpha1&quot;)<br> apiResIfs := make([]APIResourceInfo, 0)<br> for _, apiResourcesList := range serverResources {<br>  // ...<br>  // ✅ 두번째 루프는 APIResource(ex: &quot;applications&quot;, &quot;applicationsets&quot;)<br>  for _, apiResource := range apiResourcesList.APIResources {<br>    <br>   // ✅ 재외 대상 리소스인 경우 무시<br>   if resourceFilter.IsExcludedResource(gv.Group, apiResource.Kind, config.Host) {<br>    continue<br>   }<br><br>   if filter(&amp;apiResource) {<br>    resource := ToGroupVersionResource(apiResourcesList.GroupVersion, &amp;apiResource)<br>    gv, err := schema.ParseGroupVersion(apiResourcesList.GroupVersion)<br>    if err != nil {<br>     return nil, err<br>    }<br>    <br>    // ✅ 타입 정보 구성<br>    <br>    apiResIf := APIResourceInfo{<br>     GroupKind:            schema.GroupKind{Group: gv.Group, Kind: apiResource.Kind},<br>     Meta:                 apiResource,<br>     GroupVersionResource: resource,<br>    }<br>    apiResIfs = append(apiResIfs, apiResIf)<br>   }<br>  }<br> }<br> return apiResIfs, nil<br>}</pre><p>이렇게 argocd gitops-engine 내부에서 DynamicClient를 추상화하여 클러스터 접근에 관한 config를 외부에서 의존성 주입으로 가져와 명령만 수행하는 구조로 kubectl을 추상화하고 있습니다. 따라서 Kubectl 인터페이스는 다른 클러스터의 config만 있으면 해당 클러스터에 대한 리소스 타입 정보를 가져올 수 있게 됩니다. 다음으로 gitops-engine 내부의 Kubectl인터페이스 구현에서 확인한 함수를 이용하여 어떻게 클러스터를 감시하기 위한 초기화를 진행하는지 확인해보겠습니다.</p><h3>ClusterCache</h3><p>ClusterCache는 클러스터 상태를 캐싱하는 역할을 수행하는 gitops-engine 내부의 인터페이스입니다. clusterCache는 이 인터페이스를 구현하고 있고 clusterCache 내부에서 클러스터와 관련된 다양한 처리를 수행합니다.</p><p>인터페이스 형식은 다음과 같습니다.</p><pre>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/cache/cluster.go#L116&gt;<br>type ClusterCache interface {<br><br>	// ✅ 클러스터 상태 동기화<br>	// EnsureSynced checks cache state and synchronizes it if necessary<br>	EnsureSynced() error<br><br>	// ✅ 클러스터 버전 &amp; 타입 &amp; 리소스 조회<br>	// GetServerVersion returns observed cluster version<br>	GetServerVersion() string<br>	// GetAPIResources returns information about observed API resources<br>	GetAPIResources() []kube.APIResourceInfo<br>	// GetOpenAPISchema returns open API schema of supported API resources<br>	GetOpenAPISchema() openapi.Resources<br>	// GetGVKParser returns a parser able to build a TypedValue used in<br>	// structured merge diffs.<br>	GetGVKParser() *managedfields.GvkParser<br>	// Invalidate cache and executes callback that optionally might update cache settings<br>	Invalidate(opts ...UpdateSettingsFunc)<br>	// FindResources returns resources that matches given list of predicates from specified namespace or everywhere if specified namespace is empty<br>	FindResources(namespace string, predicates ...func(r *Resource) bool) map[kube.ResourceKey]*Resource<br>	// IterateHierarchy iterates resource tree starting from the specified top level resource and executes callback for each resource in the tree.<br>	// The action callback returns true if iteration should continue and false otherwise.<br>	<br>	// ✅ 리소스에 대한 iterate<br>	IterateHierarchy(key kube.ResourceKey, action func(resource *Resource, namespaceResources map[kube.ResourceKey]*Resource) bool)<br>	// IterateHierarchyV2 iterates resource tree starting from the specified top level resources and executes callback for each resource in the tree.<br>	// The action callback returns true if iteration should continue and false otherwise.<br>	IterateHierarchyV2(keys []kube.ResourceKey, action func(resource *Resource, namespaceResources map[kube.ResourceKey]*Resource) bool)<br>	// IsNamespaced answers if specified group/kind is a namespaced resource API or not<br>	IsNamespaced(gk schema.GroupKind) (bool, error)<br>	// GetManagedLiveObjs helps finding matching live K8S resources for a given resources list.<br>	// The function returns all resources from cache for those `isManaged` function returns true and resources<br>	// specified in targetObjs list.<br>	GetManagedLiveObjs(targetObjs []*unstructured.Unstructured, isManaged func(r *Resource) bool) (map[kube.ResourceKey]*unstructured.Unstructured, error)<br>	// GetClusterInfo returns cluster cache statistics<br>	GetClusterInfo() ClusterInfo<br>	<br>	// ✅ 이벤트 등록<br>	// OnResourceUpdated register event handler that is executed every time when resource get&#39;s updated in the cache<br>	OnResourceUpdated(handler OnResourceUpdatedHandler) Unsubscribe<br>	// OnEvent register event handler that is executed every time when new K8S event received<br>	OnEvent(handler OnEventHandler) Unsubscribe<br>	// OnProcessEventsHandler register event handler that is executed every time when events were processed<br>	OnProcessEventsHandler(handler OnProcessEventsHandler) Unsubscribe<br>}</pre><p>해당 인터페이스 기능을 크게 분류하면</p><ul><li>클러스터 상태 동기화</li><li>클러스터 버전 &amp; 타입 &amp; 리소스 조회</li><li>리소스 이터레이션</li><li>이벤트 등록</li></ul><p>으로 구분할 수 있습니다. 여기서 위에서 확인한 타입 디스커버링과 관련된 기능은 EnsureSynced에서 담당하고 있습니다. 해당 메서드 구현을 살펴보겠습니다.</p><pre>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/cache/cluster.go#L995&gt;<br>func (c *clusterCache) EnsureSynced() error {<br><br>	// ... 동시성 관련 처리<br><br>	err := c.sync()<br>	<br>	// ...<br>	<br>}<br><br>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/cache/cluster.go#L867&gt;<br>func (c *clusterCache) sync() error {<br>	<br>	// ...<br><br>	// ✅ 1. 기존 리소스 감시 중단<br>	for i := range c.apisMeta {<br>		c.apisMeta[i].watchCancel()<br>	}<br>	<br>	// ... clusterCache 필드 초기화<br>	<br>	// ✅ 2. 클러스터 메타데이터 가져오기: 리소스 타입 디스커버리<br>	version, err := c.kubectl.GetServerVersion(config)<br>	apis, err := c.kubectl.GetAPIResources(c.config, true, c.settings.ResourcesFilter)<br>	openAPISchema, gvkParser, err := c.kubectl.LoadOpenAPISchema(config)<br>	apis, err := c.kubectl.GetAPIResources(c.config, true, c.settings.ResourcesFilter)<br>	<br>	// ...<br>	client, err := c.kubectl.NewDynamicClient(c.config)<br>	clientset, err := kubernetes.NewForConfig(config)<br><br>	// ✅ 3. 리소스 병렬 처리: RunAllAsync func 내부에 있는 로직을 apis 개수로 병렬 실행<br>	// Each API is processed in parallel, so we need to take out a lock when we update clusterCache fields.<br>	lock := sync.Mutex{}<br>	err = kube.RunAllAsync(len(apis), func(i int) error {<br>		api := apis[i]<br><br>		// ...<br><br>		// callback함수 실행<br>		return c.processApi(client, api, func(resClient dynamic.ResourceInterface, ns string) error {<br>			// 리소스 버전 조회<br>			resourceVersion, err := c.listResources(ctx, resClient, func(listPager *pager.ListPager) error {<br><br>				// ...<br><br>			})<br><br>			// ✅ 4. 감시 goroutine 실행<br>			go c.watchEvents(ctx, api, resClient, ns, resourceVersion)<br><br>			return nil<br>		})<br>	})<br><br>	// ...<br>}</pre><p>EnsureSynced 메서드를 확인하면 동시성 제어를 위해 락을 획득하고 sync메서드를 호출합니다. sync메서드 내부를 확인해보면 다음 작업이 이루어집니다.</p><ol><li>기존 리소스의 감시를 중단합니다.</li><li>클러스터 메타데이터를 조회합니다. 여기서 이전에 확인한 kubernetes discovery기능을 활용합니다.</li><li>리소스에 따라 병렬로 처리합니다. discovery를 통해 전달받은 api마다 병렬로 실행합니다.</li><li>리소스 버전을 조회하고 감시 메서드인 watchEvents를 호출하는 goroutine을 실행합니다.</li></ol><p>잠시 watchEvents 내부를 살펴봅시다.</p><pre>// &lt;https://github.com/argoproj/gitops-engine/blob/acb47d5407b6deedbce7d7cec20c4e6fa5e64048/pkg/cache/cluster.go#L653&gt;<br>func (c *clusterCache) watchEvents(ctx context.Context, api kube.APIResourceInfo, resClient dynamic.ResourceInterface, ns string, resourceVersion string) {<br>	kube.RetryUntilSucceed(ctx, watchResourcesRetryTimeout, fmt.Sprintf(&quot;watch %s on %s&quot;, api.GroupKind, c.config.Host), c.log, func() (err error) {<br>		<br>		// ...<br><br>		// ✅ 1. retry watcher 생성: 내부에서 watchEvents가 호출될 때<br>		// 주입한 resClient에 대한 watch를 시작<br>		// resClient는 dynamic.ResourceInterface로 kubernetes에 오브젝트에 대한 crud가 가능<br>		w, err := watchutil.NewRetryWatcher(resourceVersion, &amp;cache.ListWatch{<br>			WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {<br>				res, err := resClient.Watch(ctx, options)<br>				if apierrors.IsNotFound(err) {<br>					c.stopWatching(api.GroupKind, ns)<br>				}<br>				return res, err<br>			},<br>		})<br>		<br>		// ...<br><br>		for {<br>			select {<br>			<br>			// ...<br><br>			// ✅ 2. watcher로부터 이벤트 받기<br>			case event, ok := &lt;-w.ResultChan():<br>				if !ok {<br>					return fmt.Errorf(&quot;Watch %s on %s has closed&quot;, api.GroupKind, c.config.Host)<br>				}<br><br>				obj, ok := event.Object.(*unstructured.Unstructured)<br>				if !ok {<br>					return fmt.Errorf(&quot;Failed to convert to *unstructured.Unstructured: %v&quot;, event.Object)<br>				}<br><br>				// ✅ 3. recordEvent 호출: 이벤트 기록 함수<br>				c.recordEvent(event.Type, obj)<br>				if kube.IsCRD(obj) {<br>				<br>					// ...<br>					// crd의 경우에 대한 처리<br>				}<br>			}<br>		}<br>	})<br>}</pre><p>watchEvents는 리소스 api와 일치하는 타입에 대하여 kubernetes/client-go의 감시를 담당하는 watcher를 생성합니다. 이후 루프에서 이벤트가 발생하면 clusterCache의 recordEvent메서드를 호출합니다. 따라서 clusterCache를 통해 감시하는 대상 클러스터의 리소스에 변화가 생기면 이벤트를 watchEvents 루프 내부에서 전달받고 recordEvent를 호출한다는 것을 알 수 있습니다.</p><p>한편 recordEvent의 정의도 살펴보겠습니다</p><pre>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/cache/cluster.go#L1299&gt;<br>func (c *clusterCache) recordEvent(event watch.EventType, un *unstructured.Unstructured) {<br>	// ✅ 등록된 eventHandlers 호출<br>	for _, h := range c.getEventHandlers() {<br>		h(event, un)<br>	}<br>	key := kube.GetResourceKey(un)<br>	if event == watch.Modified &amp;&amp; skipAppRequeuing(key) {<br>		return<br>	}<br><br>	// ✅ batch 처리하거나 processEvent 호출<br>	if c.batchEventsProcessing {<br>		c.eventMetaCh &lt;- eventMeta{event, un} // batch 처리에서도 processEvent 호출<br>	} else {<br>		c.lock.Lock()<br>		defer c.lock.Unlock()<br>		c.processEvent(key, eventMeta{event, un})<br>	}<br>}<br><br>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/cache/cluster.go#L1317&gt;<br>// ✅ node 이벤트에 따라 삭제 또는 업데이트 진행<br>func (c *clusterCache) processEvent(key kube.ResourceKey, evMeta eventMeta) {<br>	existingNode, exists := c.resources[key]<br>	<br>	// ✅ clusterCache에 등록된 ResourceUpdatedHandlers 호출<br>	if evMeta.event == watch.Deleted {<br>		if exists {<br>			c.onNodeRemoved(key)<br>		}<br>	} else {<br>		c.onNodeUpdated(existingNode, c.newResource(evMeta.un))<br>	}<br>}<br><br>func (c *clusterCache) onNodeUpdated(oldRes *Resource, newRes *Resource) {<br>	c.setNode(newRes)<br>	for _, h := range c.getResourceUpdatedHandlers() {<br>		h(newRes, oldRes, c.nsIndex[newRes.Ref.Namespace])<br>	}<br>}<br><br>func (c *clusterCache) onNodeRemoved(key kube.ResourceKey) {<br>	existing, ok := c.resources[key]<br>	if ok {<br>		delete(c.resources, key)<br>		<br>		// ...<br>		<br>		for _, h := range c.getResourceUpdatedHandlers() {<br>			h(nil, existing, ns)<br>		}<br>	}<br>}</pre><p>recordEvent가 호출되면 clusterCache는 등록된 이벤트 핸들러를 호출합니다. 여기서 핸들러가 두 종류로 보이는데, 하나는 getEventHandlers로 가져오는 핸들러이고 다른 하나는 node 수준에서 발생하는 getResourceUpdatedHandlers입니다.</p><p>그럼 ClusterCache의 이벤트 처리 관련 메서드에 대한 정의를 살펴보지 않아도 동작을 예상할 수 있습니다.</p><pre>type ClusterCache interface {<br>	// ...<br>	// ✅ 이벤트 등록<br>	// OnResourceUpdated register event handler that is executed every time when resource get&#39;s updated in the cache<br>	OnResourceUpdated(handler OnResourceUpdatedHandler) Unsubscribe // onNodeUpdated &amp; onNodeDeleted가 호출됐을 때 실행할 callback 목록<br>	// OnEvent register event handler that is executed every time when new K8S event received<br>	OnEvent(handler OnEventHandler) Unsubscribe // recordEvent가 호출됐을 때 실행할 callback 목록<br>}</pre><p>그럼 ClusterCache의 동작 흐름을 요약해보면 다음과 같습니다.</p><ol><li>gitops-engine 외부에서 EnsureSynced를 호출하면 락을 획득하고 sync를 호출합니다.</li><li>sync 내에서 관찰할 cluster를 디스커버리하고 관측할 api 수마다 goroutine을 생성하며 watchEvents를 호출합니다.</li><li>watchEvents 내부에서 반복문으로 이벤트 감시를 대기하고 이벤트가 발생할 때마다 recordEvent를 호출합니다.</li><li>recordEvent에서 clusterCache에 등록된 이벤트 callback함수를 실행합니다.</li></ol><p>이를 다이어그램으로 표현하면 다음과 같이 나타낼 수 있습니다.</p><pre>sequenceDiagram<br>    participant EnsureSynced as EnsureSynced<br>    participant Sync as Sync<br>    participant Discovery as Cluster Discovery<br>    participant Watch as Watch Events<br>    participant Record as Record Event<br><br>    EnsureSynced-&gt;&gt;EnsureSynced: EnsureSynced 호출<br>    EnsureSynced-&gt;&gt;Sync: 락 획득 후 sync 호출<br>    Sync-&gt;&gt;Discovery: 클러스터 디스커버리<br>    Discovery-&gt;&gt;Sync: 관찰할 클러스터 리스트 반환<br>    Sync-&gt;&gt;Sync: api 수만큼 goroutine 생성<br>    Sync-&gt;&gt;Watch: watchEvents 호출<br>    Watch-&gt;&gt;Watch: 이벤트 대기<br>    Watch-&gt;&gt;Record: 이벤트 발생 시 recordEvent 호출<br>    Record-&gt;&gt;Record: 등록된 callback 함수 실행</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*HRZLwg1sW5G4bYzy-gc3EQ.png" /></figure><p>그럼 ClusterCache가 관측할 클러스터의 리소스 타입을 런타임에 감지하고 클러스터의 리소스가 변화했을 때 등록된 callback을 실행한다는 것을 알았습니다. 그럼 다음에는 argocd와 ClusterCache가 어떻게 상호작용하는지 분석해보겠습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2315d9edd741" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[golang 비동기. tcp서버(6). netpoll 3부. golang 내부 epoll 활용: read & write]]></title>
            <link>https://medium.com/@hyper201286/golang-%EB%B9%84%EB%8F%99%EA%B8%B0-tcp%EC%84%9C%EB%B2%84-6-netpoll-3%EB%B6%80-golang-%EB%82%B4%EB%B6%80-epoll-%ED%99%9C%EC%9A%A9-read-write-8d84e7fd26f8?source=rss-619cbfeff5b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d84e7fd26f8</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[socket-programming]]></category>
            <dc:creator><![CDATA[flangdu]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 06:26:04 GMT</pubDate>
            <atom:updated>2024-12-23T06:26:04.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwnCe6sFIa3_gK8qa80-wA.png" /></figure><p>해당 아티클은 다음 수준의 지식을 요구합니다.</p><ul><li>POSIX 네트워크 syscall</li><li>epoll</li></ul><p>이전 아티클 “golang 비동기. tcp 서버(5). netpoller 2부. golang 내부 epoll 활용: Accept”를 보시는 걸 권장합니다. 이번에는 read와 write하는 부분이 어떻게 일어나는지 추적해보겠습니다.</p><p>예시로 살펴보는 지점은 다음 코드의 ✅ 부분입니다.</p><pre>func main() {<br>	listener, err := net.Listen(&quot;tcp&quot;, &quot;:8989&quot;)<br>	if err != nil {<br>		fmt.Println(&quot;listen error&quot;, err)<br>		return<br>	}<br><br>	for {<br>		conn, err := listener.Accept()<br>		if err != nil {<br>			fmt.Println(&quot;accept error&quot;, err)<br>			continue<br>		}<br>		go func() {<br>			b := make([]byte, 4096)<br>			for {<br>				// ✅ read 내부<br>				n, err := conn.Read(b)<br>				if err != nil {<br>					fmt.Println(&quot;read error&quot;, n)<br>					return<br>				}<br><br>				// ✅ write 내부<br>				if _, err := conn.Write(b); err != nil {<br>					fmt.Println(&quot;write error&quot;, n)<br>					return<br>				}<br>			}<br>		}()<br>	}<br>}</pre><h3>1. Read 내부</h3><p>(net.Conn).Read가 진행되는 과정은 Accept가 진행되는 과정과 매우 유사합니다. Read또한 FD의 Read부터 코드를 확인해보겠습니다.</p><pre>// &lt;https://github.com/golang/go/blob/194de8fbfaf4c3ed54e1a3c1b14fc67a830b8d95/src/internal/poll/fd_unix.go#L141&gt;<br>func (fd *FD) Read(p []byte) (int, error) {<br>	// ✅ readLock을 획득: 하나의 conn에서 여러 고루틴이 Read를 호출해도<br>	// 하나의 고루틴만 로직이 진행<br>	if err := fd.readLock(); err != nil {<br>		return 0, err<br>	}<br>	defer fd.readUnlock()<br>	<br>	// 바이트 배열의 크기를 0으로 주었다면 무시<br>	if len(p) == 0 {<br>		// ...<br>		return 0, nil<br>	}<br>	<br>	// Read 준비<br>	if err := fd.pd.prepareRead(fd.isFile); err != nil {<br>		return 0, err<br>	}<br>	<br>	// ...<br><br>	for {<br>		// ✅ read syscall 호출<br>		n, err := ignoringEINTRIO(syscall.Read, fd.Sysfd, p)<br>		if err != nil {<br>			n = 0<br>			<br>			// ✅ 만약 non-blocking에 의한 데이터가 도착하지 않아 읽을 수 없는 상태라면<br>			if err == syscall.EAGAIN &amp;&amp; fd.pd.pollable() {<br>				if err = fd.pd.waitRead(fd.isFile); err == nil {<br>					continue<br>				}<br>			}<br>		}<br>		// ✅ 읽은 데이터가 존재하는 경우 바로 return 절로 이동<br>		err = fd.eofError(n, err)<br>		return n, err<br>	}<br>}</pre><p>Accept랑 비교해보면 매우 유사한 점이 많습니다. 함수 동작을 요약하면 다음과 같습니다.</p><ol><li>readLock을 획득합니다. 따라서 같은 fd에서 접근하는 Read요청에 대하여 하나의 고루틴만 진입하도록 합니다.</li><li>Read를 준비합니다. 여기서 Read란 소켓으로부터 수신된 데이터가 존재하는 경우를 의미합니다.</li><li>read를 호출합니다. 논블로킹 소켓이기 때문에 바로 리턴됩니다.</li><li>만약 읽은 데이터가 존재하는 경우 바로 읽은 바이트 배열과 함께 리턴됩니다.</li><li>만약 읽은 데이터가 존재하지 않는 경우 EAGAIN 분기로 처리됩니다. 해당 분기에서 fd.pd.WaitRead를 호출하여 데이터가 존재할 때까지 고루틴을 대기합니다.</li></ol><h3>2. Write 내부</h3><p>write가 진행되는 부분도 *FD.Write부분부터 시작하겠습니다.</p><pre>// &lt;https://github.com/golang/go/blob/194de8fbfaf4c3ed54e1a3c1b14fc67a830b8d95/src/internal/poll/fd_unix.go#L367&gt;<br>func (fd *FD) Write(p []byte) (int, error) {<br>	// ✅ writeLock을 획득: 하나의 conn에서 여러 고루틴이 Write를 호출해도<br>	// 하나의 고루틴만 로직이 진행<br>	if err := fd.writeLock(); err != nil {<br>		return 0, err<br>	}<br>	defer fd.writeUnlock()<br>	<br>	// Write 준비<br>	if err := fd.pd.prepareWrite(fd.isFile); err != nil {<br>		return 0, err<br>	}<br>	<br>	// ✅ 지금까지 써진 데이터<br>	var nn int<br>	for {<br>		max := len(p)<br>		if fd.IsStream &amp;&amp; max-nn &gt; maxRW {<br>			max = nn + maxRW<br>		}<br>		<br>		// ✅ write syscall 호출<br>		n, err := ignoringEINTRIO(syscall.Write, fd.Sysfd, p[nn:max])<br>			<br>			// ...<br>			<br>			// ✅ 써진 데이터를 누적시킴<br>			nn += n<br>		}<br>		<br>		// ✅ 만약 쓰인 데이터가 입력 데이터 크기와 같은 경우 종료<br>		if nn == len(p) {<br>			return nn, err<br>		}<br>		<br>		// ✅ write를 일시적으로 할 수 없는 상태인 경우 write 고루틴이 활성화될 때까지 대기<br>		if err == syscall.EAGAIN &amp;&amp; fd.pd.pollable() {<br>			if err = fd.pd.waitWrite(fd.isFile); err == nil {<br>				continue<br>			}<br>		}<br>		<br>		// ✅ 에러 및 EOF 처리<br>		if err != nil {<br>			return nn, err<br>		}<br>		if n == 0 {<br>			return nn, io.ErrUnexpectedEOF<br>		}<br>	}<br>}</pre><p>write또한 read과정과 유사합니다.</p><ol><li>writeLock을 획득합니다. 따라서 같은 fd에서 접근하는 Write요청에 대하여 하나의 고루틴만 진입하도록 합니다.</li><li>Write를 준비합니다. 여기서 Write란 소켓으로부터 송신할 데이터가 존재하는 경우를 의미합니다.</li><li>write를 호출합니다. 논블로킹 소켓이기 때문에 바로 리턴됩니다.</li><li>쓴 데이터를 전체에서 얼마만큼 썼는지 누적 길이 nn에 저장합니다.</li><li>만약 누적 길이 nn이 쓴 데이터의 크기와 같다면 리턴합니다.</li><li>당장 데이터를 쓸 수 없는 에러가 발생한 경우 fd.pd.waitWrite를 호출하여 다시 쓸 수 있는 상태가 될 때까지 고루틴을 대기시킵니다.</li><li>에러가 존재하는 경우, 기존에 썼던 크기와 함께 에러를 리턴합니다.</li></ol><p>이후 비활성화 &amp; 활성화 로직은 accept 과정과 유사하게 동작합니다.</p><p>비활성화 과정에서 read와 write 모두 WaitRead, WaitWrite를 호출하여 netpollblock 내에서 고루틴이 대기하게 됩니다. 고루틴이 대기할 때 gopark에서 최종으로 호출하는 netpollblockcommit 함수 내에서 고루틴의 정보를 저장합니다. 읽기와 쓰기는 pollDesc 내부에서 rg, wg를 활용하는지 정도의 차이가 존재합니다.</p><p>읽기와 쓰기는 따로 이벤트가 관리됩니다. 이 이유는 쓰기와 읽기 중 하나만 일시적인 에러이고 다른 하나는 정상으로 동작하는 상태일 수 있기 때문입니다. 이에 대한 코드는 앞에서도 확인했지만 netpoll 코드에서 볼 수 있습니다.</p><pre>// &lt;https://github.com/golang/go/blob/194de8fbfaf4c3ed54e1a3c1b14fc67a830b8d95/src/runtime/netpoll_epoll.go#L96&gt;<br>func netpoll(delay int64) (gList, int32) {<br>	// ...<br>	<br>	// ✅ epollwait로 이벤트 수신 대기<br>	n, errno := syscall.EpollWait(epfd, events[:], int32(len(events)), waitms)<br>	<br>	for i := int32(0); i &lt; n; i++ {<br>		ev := events[i]<br>		<br>		// ...<br>		<br>		// ✅ 일치하는 이벤트에 따라 분기 처리<br>		if ev.Events&amp;(syscall.EPOLLIN|syscall.EPOLLRDHUP|syscall.EPOLLHUP|syscall.EPOLLERR) != 0 {<br>			mode += &#39;r&#39;<br>		}<br>		if ev.Events&amp;(syscall.EPOLLOUT|syscall.EPOLLHUP|syscall.EPOLLERR) != 0 {<br>			mode += &#39;w&#39;<br>		}<br>		<br>		// ✅ mode가 존재하는 경우 netpollready에서 고루틴 활성화<br>		if mode != 0 {<br>			tp := *(*taggedPointer)(unsafe.Pointer(&amp;ev.Data))<br>			pd := (*pollDesc)(tp.pointer())<br>			tag := tp.tag()<br>			if pd.fdseq.Load() == tag {<br>				pd.setEventErr(ev.Events == syscall.EPOLLERR, tag)<br>				delta += netpollready(&amp;toRun, pd, mode)<br>			}<br>		}<br>	}<br>	return toRun, delta<br>}</pre><p>이 함수를 호출하는 대상 또한 accept에서 확인했던 바와 동일하게 아래와 같은 방식으로 활성화됩니다.</p><ol><li>netpoll은 sysmon, findRunnable등 고루틴 런타임 내부 함수로부터 호출됩니다.</li><li>netpoll호출 시 epollwait로 리턴받은 이벤트 리스트로 고루틴 리스트를 추출합니다.</li><li>sysmon은 grq에, findRunnable은 rlq에 고루틴을 저장합니다.</li></ol><p>여기까지 netpoll을 이용한 golang의 소켓 R/W 동작을 살펴봤습니다. R/W과정을 대체로 유사하게 동작하며 “syscall 호출” → “EAGAIN이면 고루틴 대기” → “외부에서 활성화 호출하여 대기가 끝난 고루틴 해제” 과정을 거친다는 것을 알아봤습니다. 이후 고루틴 해제 과정이 지나면 런타임의 runnable queue에 실행 대기 상태의 고루틴을 넣어 쓰레드 위에서 고루틴이 실행될 수 있도록 합니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d84e7fd26f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[argocd 분석: app controller의 k8s 리소스 sync]]></title>
            <link>https://medium.com/@hyper201286/argocd-%EB%B6%84%EC%84%9D-app-controller%EC%9D%98-k8s-%EB%A6%AC%EC%86%8C%EC%8A%A4-sync-7228374d88b7?source=rss-619cbfeff5b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7228374d88b7</guid>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[flangdu]]></dc:creator>
            <pubDate>Sat, 21 Dec 2024 05:42:38 GMT</pubDate>
            <atom:updated>2024-12-21T05:42:38.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*bO3GF_tJsJAM1--dUqiJmw.png" /></figure><p>다시 application controller로 돌아와서 CompareAppState라는 함수를 살펴봅시다. 해당 함수는 원격 저장소와 대상 클러스터 사이의 차이를 찾아 재조정할 대상을 정하는 역할을 했습니다. 이번에는 application controller에서 차이가 발생한 대상을 재조정하는 과정을 탐색해보겠습니다.</p><h3>processAppRefreshQueueItem의 최하층</h3><p>지금까지 확인한 코드를 살펴보면 applications의 상태를 가져와 원격 저장소와 비교하고 sync할 대상을 탐색하여 app을 갱신하는 코드까지 확인했습니다. 이제는 갱신된 app을 통하여 어떻게 k8s 리소스가 생성되는지 비교해보도록 하겠습니다.</p><p>다시 processAppRefreshQueueItem을 살펴보면 defer로 호출되는 절이 있습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/appcontroller.go#L1541&gt;<br>func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext bool) {<br>	<br>	// ...<br>	<br>	defer func() {<br>		if r := recover(); r != nil {<br>			log.Errorf(&quot;Recovered from panic: %+v\\n%s&quot;, r, debug.Stack())<br>		}<br>		// We want to have app operation update happen after the sync, so there&#39;s no race condition<br>		// and app updates not proceeding. See &lt;https://github.com/argoproj/argo-cd/issues/18500&gt;.<br>		// ✅ 이 부분에서 refresh queue -&gt; operation queue로 넘어감<br>		ctrl.appOperationQueue.AddRateLimited(appKey)<br>		ctrl.appRefreshQueue.Done(appKey)<br>	}()<br>	<br>	// ...</pre><p>processAppRefreshQueueItem 함수가 종료됐을 때 호출되는 부분으로 defer절 내부가 실행됩니다. 이 내부에서 ctrl.appOperationQueue.AddRateLimited(appKey) 에서 RefreshQueue → OperationQueue로 동작이 이동합니다. appKey를 넘겨 RefreshQueue에서 처리한 대상을 Operation Queue로 전달합니다. 이때 Operation Queue에 전달된 이벤트는 processAppOperationItem이라는 함수가 실행합니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/appcontroller.go#L934&gt;<br>func (ctrl *ApplicationController) processAppOperationQueueItem() (processNext bool) {<br>	// ✅ queue data 가져오기<br>	appKey, shutdown := ctrl.appOperationQueue.Get()<br>	<br>	// ...<br>	<br>	// ✅ informer에서 object 조회<br>	obj, exists, err := ctrl.appInformer.GetIndexer().GetByKey(appKey)<br>	<br>	// ...<br><br>	// ✅ operation이 nil이 아닐 때<br>	if app.Operation != nil {<br>		ctrl.processRequestedAppOperation(app)<br>		ts.AddCheckpoint(&quot;process_requested_app_operation_ms&quot;)<br>	}<br>	<br>	// ...<br>	<br>}</pre><p>Operation Queue 내부는 appKey로 app 오브젝트를 조회하고 operation이 존재하는 경우 processRequestedAppOperation 메서드로 app을 전달합니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/appcontroller.go#L1317&gt;<br>func (ctrl *ApplicationController) processRequestedAppOperation(app *appv1.Application) {<br><br>	// ...<br><br>	if isOperationInProgress(app) {<br>		// 이미 처리중인 경우 종료가 아니면 retry 로직<br>	} else {<br>		<br>		// app phase를 operation running으로 변경<br>		state = &amp;appv1.OperationState{Phase: synccommon.OperationRunning, Operation: *app.Operation, StartedAt: metav1.Now()}<br>		ctrl.setOperationState(app, state)<br>		// ...<br>	}<br><br>	// 목적지 검증 후<br>	if err := argo.ValidateDestination(context.Background(), &amp;app.Spec.Destination, ctrl.db); err != nil {<br>		<br>		// ...<br>		<br>		// ✅ 에러가 없는 경우 SyncAppState 호출<br>	} else {<br>		ctrl.appStateManager.SyncAppState(app, state)<br>	}<br>	<br>	// ...<br>	// app state 재검사<br>	<br>}</pre><p>이 부분은 app에 대한 “검증” → “생성” → “생성 이후 살태에 대한 로직 처리”로 진행됩니다. 주요한 함수로 SyncAppState라는 함수가 있는데 이 부분에서 실제 k8s 오브젝트의 재조정이 일어납니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/sync.go#L90&gt;<br>func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha1.OperationState) {<br>	// ...<br><br>	// ✅ CompareAppState 재호출<br>	compareResult, err := m.CompareAppState(app, proj, revisions, sources, false, true, syncOp.Manifests, isMultiSourceRevision, rollback)<br><br>	// ...<br><br>	// ✅ 클러스터 조회<br>	clst, err := m.db.GetCluster(context.Background(), app.Spec.Destination.Server)<br>	<br>	// ...<br>	<br>	// ✅ syncCtx 생성<br>	syncCtx, cleanup, err := sync.NewSyncContext(<br>		// ...<br>	)<br>	<br>	// ...<br><br>	if state.Phase == common.OperationTerminating {<br>		syncCtx.Terminate()<br>	} else {<br>		// ✅ terminating이 아니면 Sync 진행<br>		syncCtx.Sync()<br>	}<br>	<br>	// ...<br>}</pre><p>함수 내부는 크게 다음 로직이 실행됩니다.</p><ul><li>CompareAppState 재호출로 CompareResult 추출</li><li>클러스터 조회</li><li>syncCtx 생성</li><li>syncCtx.Sync 호출</li></ul><p>여기서 실제로 sync를 수행하는 함수는 syncCtx의 Sync 메서드입니다. syncContext는 sync.NewSyncContext 함수로부터 생성되는데 이 함수는 argocd내부의 코드가 아닙니다. 이 함수는 gitops-engine이라는 라이브러리 코드로부터 호출됩니다.</p><p>gitops-engine은 argocd와 fluxcd가 공동으로 사용하는 gitops 엔진입니다. 통합에 관련된 자세한 사항은 아래 문서를 참고하시기 바랍니다.</p><p><a href="https://github.com/argoproj/gitops-engine/blob/master/docs/faq.md">https://github.com/argoproj/gitops-engine/blob/master/docs/faq.md</a></p><p>gitops engine의 Sync메서드는 다음과 같이 동작합니다.</p><pre>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/sync/sync_context.go#L394&gt;<br>func (sc *syncContext) Sync() {<br>	// ...<br><br>	if sc.started() {<br>		// ...<br>	} else {<br>	<br>		// ...<br>		<br>		// ✅ dry run으로 사전 동작 체크<br>		dryRunTasks := tasks<br>		if sc.applyOutOfSyncOnly {<br>			dryRunTasks = sc.filterOutOfSyncTasks(tasks)<br>		}<br><br>		sc.log.WithValues(&quot;tasks&quot;, dryRunTasks).Info(&quot;Tasks (dry-run)&quot;)<br>		if sc.runTasks(dryRunTasks, true) == failed {<br>			sc.setOperationPhase(common.OperationFailed, &quot;one or more objects failed to apply (dry run)&quot;)<br>			return<br>		}<br>	}<br><br>	// ...<br>	// sync 시 hook &amp; phase 설정<br>	// ...<br>	<br>	// ✅ 실제 kubernetes apply 실행<br>	runState := sc.runTasks(tasks, false)<br><br>	// runState에 대한 상태 분기 처리<br>}</pre><p>Sync 는 dry-run으로 생성 테스트를 수행하고 올바른 경우 runTasks 메서드를 호출합니다. 실제 kubectl apply와 같은 역할은 runTasks에서 일어납니다. 이 함수 내부는 다음과 같습니다. 여기서는 생성 부분을 주로 다루겠습니다.</p><pre>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/sync/sync_context.go#L1155&gt;<br>func (sc *syncContext) runTasks(tasks syncTasks, dryRun bool) runState {<br>	<br>	// ...<br><br>	// tasks에 대한 분리 작업<br>	for _, task := range tasks {<br>		if task.isPrune() {<br>			pruneTasks = append(pruneTasks, task)<br>		} else {<br>			createTasks = append(createTasks, task)<br>		}<br>	}<br>	<br>	// prune 처리<br>	// ...<br><br>	// delete 처리<br>	// ...<br><br>	var tasksGroup syncTasks<br><br>	// ...<br>	<br>	if len(tasksGroup) &gt; 0 {<br>		// ✅ 리소스 생성 처리<br>		state = sc.processCreateTasks(state, tasksGroup, dryRun)<br>	}<br>	<br>	return state<br>}<br><br>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/sync/sync_context.go#L1265&gt;<br>func (sc *syncContext) processCreateTasks(state runState, tasks syncTasks, dryRun bool) runState {<br>	ss := newStateSync(state)<br>	for _, task := range tasks {<br>		// dryRun인 경우 스킵<br>		if dryRun &amp;&amp; task.skipDryRun {<br>			continue<br>		}<br>		t := task<br>		ss.Go(func(state runState) runState {<br>			<br>			// ...<br>			<br>			// ✅ 고루틴으로 applyObject로 리소스 생성 호출<br>			result, message := sc.applyObject(t, dryRun, validate)<br>			<br>			// ...<br>			<br>			return state<br>		})<br>	}<br>	return ss.Wait()<br>}<br><br>// &lt;https://github.com/argoproj/gitops-engine/blob/54992bf42431e71f71f11647e82105530e56305e/pkg/sync/sync_context.go#L968&gt;<br>func (sc *syncContext) applyObject(t *syncTask, dryRun, validate bool) (common.ResultCode, string) {<br>	<br>	// ...<br>	<br>	if shouldReplace { // ✅ replace인 경우<br>		if t.liveObj != nil { // ✅ 이미 리소스가 있을 때<br>			// ...<br>			// crd나 ns kind인 경우: kubectl replace 대신 update resource<br>			if kube.IsCRD(t.targetObj) || t.targetObj.GetKind() == kubeutil.NamespaceKind {<br>				<br>				// ...<br>				<br>				_, err = sc.resourceOps.UpdateResource(context.TODO(), update, dryRunStrategy)<br>				<br>				// ...<br>				<br>			} else {<br>				// ✅ crd, ns kind가 아니면 replace<br>				message, err = sc.resourceOps.ReplaceResource(context.TODO(), t.targetObj, dryRunStrategy, force)<br>			}<br>		} else {<br>			// ✅ 리소스 없으면 create<br>			message, err = sc.resourceOps.CreateResource(context.TODO(), t.targetObj, dryRunStrategy, validate)<br>		}<br>	} else { // ✅ replace가 아니면 apply<br>		message, err = sc.resourceOps.ApplyResource(context.TODO(), t.targetObj, dryRunStrategy, force, validate, serverSideApply, sc.serverSideApplyManager, false)<br>	}<br>	<br>	// ...<br>	<br>	// ✅ crd인 경우 crd 대기<br>	if kube.IsCRD(t.targetObj) &amp;&amp; !dryRun {<br>		crdName := t.targetObj.GetName()<br>		if err = sc.ensureCRDReady(crdName); err != nil {<br>			sc.log.Error(err, fmt.Sprintf(&quot;failed to ensure that CRD %s is ready&quot;, crdName))<br>		}<br>	}<br>	return common.ResultCodeSynced, message<br>}</pre><p>runTasks 내부는 create 뿐만 아니라 prune과 delete 작업을 포함합니다. create관련 작업을 보자면 processCreateTasks 를 호출하여 생성 작업을 여러 고루틴으로 처리하여 동시에 applyObject를 진행하도록 합니다. 이때 applyObject내부에는 이미 존재하는 오브젝트인지, crd인지, 존재하지 않았는지 여부에 대한 리소스 분기 처리를 시도합니다. crd나 ns kind인 경우 리소스 삭제를 방지하기 위해 리소스별 실행하는 명령을 분기하여 처리합니다.</p><p>지금까지 argocd에서 application을 생성하는 과정을 요약해보면 다음과 같이 동작함을 알 수 있습니다.</p><ol><li>cli에서 app 생성 요청을 grpc로 전달합니다.</li><li>api server는 grpc요청을 수신하고 application을 생성합니다.</li><li>생성된 application은 controller의 informer를 통해 이벤트로 전달됩니다.</li><li>refresh queue에 오브젝트가 전달되고 CompareAppState 메서드가 실행됩니다.</li><li>내부에서 repo server에 grpc 요청으로 manifest를 조회하고 repo server는 manifest를 구성하여 전달합니다.</li><li>manifest를 통하여 대상 클러스터에 배포된 내역과 비교하여 재조정할 오브젝트를 생성합니다.</li><li>operation queue로 재조정할 app에 대한 key를 전달하고 operation queue 내부에서 SyncAppState를 호출합니다.</li><li>SyncAppState 내부에서 gitops engine의 sync context를 만들고 Sync 메서드를 호출합니다.</li><li>Sync 메서드 내부에서 동기화할 리소스의 tasks를 만들고 여러 고루틴으로 동기화를 진행합니다.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7228374d88b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[argocd 분석: app controller와 repo server의 상호 작용]]></title>
            <link>https://medium.com/@hyper201286/argocd-%EB%B6%84%EC%84%9D-app-controller%EC%99%80-repo-server%EC%9D%98-%EC%83%81%ED%98%B8-%EC%9E%91%EC%9A%A9-2867a004fa8e?source=rss-619cbfeff5b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2867a004fa8e</guid>
            <category><![CDATA[argo]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[flangdu]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 16:35:04 GMT</pubDate>
            <atom:updated>2024-12-20T16:35:04.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*bO3GF_tJsJAM1--dUqiJmw.png" /></figure><p>argocd에는 repo-server라는 컴포넌트가 존재합니다. 이 컴포넌트는 manifest가 저장된 원격 저장소를 관리하는 서비스로 k8s manifest를 생성하고 반환합니다. 이전 아티클에서 argocd가 gitops를 구현하기 위해 CompareAppState 라는 메서드를 호출했는데 이 함수 내에는 repo-server로 요청하는 부분이 존재합니다. 이번에는 repo-server로 어디서 보내고 어떻게 처리하는 지 확인해보겠습니다.</p><h3>application controller → repo server 호출</h3><p>application controller에서 repo server로 요청을 호출하는 부분을 확인하려면 CompareAppState 함수를 확인해야 합니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/state.go#L429&gt;<br>func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1alpha1.AppProject, revisions []string, sources []v1alpha1.ApplicationSource, noCache bool, noRevisionCache bool, localManifests []string, hasMultipleSources bool, rollback bool) (*comparisonResult, error) {<br><br>	// ...<br><br>	<br>	if len(localManifests) == 0 {<br><br>		// ...<br>		<br>		// ✅ 1. 원격 저장소에서 대상 object 조회<br>		targetObjs, manifestInfos, revisionUpdated, err = m.GetRepoObjs(app, sources, appLabelKey, revisions, noCache, noRevisionCache, verifySignature, project, rollback)<br>		<br>		// ...<br><br>	}</pre><p>이 함수에는 GetRepoObjs 메서드를 호출하는 부분이 있습니다. 메서드 내부 구현의 주요 부분을 살펴보면 다음과 같습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/state.go#L127&gt;<br>func (m *appStateManager) GetRepoObjs(app *v1alpha1.Application, sources []v1alpha1.ApplicationSource, appLabelKey string, revisions []string, noCache, noRevisionCache, verifySignature bool, proj *v1alpha1.AppProject, rollback bool) ([]*unstructured.Unstructured, []*apiclient.ManifestResponse, bool, error) {<br><br>	// ...<br><br>	// ✅ repoClientSet으로부터 grpc client 생성<br>	conn, repoClient, err := m.repoClientset.NewRepoServerClient()<br>	<br>	// ..<br>	<br>	for i, source := range sources {<br>		<br>		// ...<br>		<br>		// ✅ repoClient에 GenerateManifest rpc호출<br>		manifestInfo, err := repoClient.GenerateManifest(context.Background(), &amp;apiclient.ManifestRequest{<br>			// ...<br>		})<br>		<br>		// ...<br>		// manifest 구성<br><br>	}<br>	<br>	// ...<br>	<br>}</pre><p>여기서 NewRepoServerClient 메서드를 들어가면 grpc client를 생성하는 부분을 확인할 수 있습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/reposerver/apiclient/clientset.go#L48&gt;<br>func (c *clientSet) NewRepoServerClient() (io.Closer, RepoServerServiceClient, error) {<br>	conn, err := NewConnection(c.address, c.timeoutSeconds, &amp;c.tlsConfig)<br>	if err != nil {<br>		return nil, nil, fmt.Errorf(&quot;failed to open a new connection to repo server: %w&quot;, err)<br>	}<br>	return conn, NewRepoServerServiceClient(conn), nil<br>}<br><br>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/reposerver/apiclient/clientset.go#L56&gt;<br>// 함수 개형만 확인: grpc 클라이언트 연결 생성<br>func NewConnection(address string, timeoutSeconds int, tlsConfig *TLSConfiguration) (*grpc.ClientConn, error) { ... }</pre><p>함수 내부를 확인하면 grpc client와 repo server에 대한 클라이언트를 생성하는 것을 확인할 수 있습니다. 따라서 NewRepoServerClient 메서드를 호출하여 grpc클라이언트를 만들고 GenerateManifest rpc를 호출합니다. 그럼 GenerateManifest가 어디서 구현되는지 찾아보겠습니다.</p><h3>repo server rpc 호출</h3><p>repo server도 cli부터 찾아볼 수 있지만, 여기서는 rpc 구현만 집중해서 확인하겠습니다. GenerateManifest에 대한 세부 구현은 다음과 같습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/reposerver/repository/repository.go#L515&gt;<br>func (s *Service) GenerateManifest(ctx context.Context, q *apiclient.ManifestRequest) (*apiclient.ManifestResponse, error) {<br><br>	// ...<br>	<br>	var promise *ManifestResponsePromise<br>	<br>	// ✅ 비동기 실행 함수<br>	operation := func(repoRoot, commitSHA, cacheKey string, ctxSrc operationContextSrc) error {<br>		<br>		// ...<br><br>		// ✅ 주요 함수: manifest 생성 호출<br>		// promise capture<br>		promise = s.runManifestGen(ctx, repoRoot, commitSHA, cacheKey, ctxSrc, q)<br>		// The fist channel to send the message will resume this operation.<br>		// The main purpose for using channels here is to be able to unlock<br>		// the repository as soon as the lock in not required anymore. In<br>		// case of CMP the repo is compressed (tgz) and sent to the cmp-server<br>		// for manifest generation.<br>		select {<br>		case err := &lt;-promise.errCh:<br>			return err<br>		case resp := &lt;-promise.responseCh:<br>			res = resp<br>		case tarDone := &lt;-promise.tarDoneCh:<br>			tarConcluded = tarDone<br>		}<br>		return nil<br>	}<br><br>	// ...<br>	<br>	// ✅ 싫제 operation은 runRepoOperation 내부에서 실행<br>	err = s.runRepoOperation(ctx, q.Revision, q.Repo, q.ApplicationSource, q.VerifySignature, cacheFn, operation, settings, q.HasMultipleSources, q.RefSources)<br><br>	// ...<br><br>	return res, err<br>}<br><br>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/reposerver/repository/repository.go#L286&gt;<br>func (s *Service) runRepoOperation(<br>	// ...<br>) error {<br><br>// ...<br><br>	// ✅ helm 분기나 helm이 아닌 분기나 operation을 함수 내부에서 호출<br>	// 다만 차이점은 operation에 전달하는 ctxSrc인자가 다름 <br>	if source.IsHelm() {<br>		<br>		// ...<br>	<br>		return operation(chartPath, revision, revision, func() (*operationContext, error) {<br>			return &amp;operationContext{chartPath, &quot;&quot;}, nil<br>		})<br>	} else {<br>		<br>		// ...<br>		<br>		// Here commitSHA refers to the SHA of the actual commit, whereas revision refers to the branch/tag name etc<br>		// We use the commitSHA to generate manifests and store them in cache, and revision to retrieve them from cache<br>		return operation(gitClient.Root(), commitSHA, revision, func() (*operationContext, error) {<br>			var signature string<br>			if verifyCommit {<br>				// When the revision is an annotated tag, we need to pass the unresolved revision (i.e. the tag name)<br>				// to the verification routine. For everything else, we work with the SHA that the target revision is<br>				// pointing to (i.e. the resolved revision).<br>				var rev string<br>				if gitClient.IsAnnotatedTag(revision) {<br>					rev = unresolvedRevision<br>				} else {<br>					rev = revision<br>				}<br>				signature, err = gitClient.VerifyCommitSignature(rev)<br>				if err != nil {<br>					return nil, err<br>				}<br>			}<br>			appPath, err := argopath.Path(gitClient.Root(), source.Path)<br>			if err != nil {<br>				return nil, err<br>			}<br>			return &amp;operationContext{appPath, signature}, nil<br>		})<br>	}<br>}</pre><p>GenerateManifest 함수 내부에는 클로저로 operation 을 선언하고 클로저를 runRepoOperation 에 전달하여 실행합니다. runRepoOperation은 내부에서 Operation을 직접 호출합니다. 결국 중요한 건 operation 내부 동작하는 로직입니다. 여기서 runManifestGen 함수의 동작이 operation의 핵심입니다. 이 함수에서 manifest를 생성하게 됩니다.</p><p>그럼 runManifestGen함수를 확인해봅시다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/reposerver/repository/repository.go#L677&gt;<br>func (s *Service) runManifestGen(ctx context.Context, repoRoot, commitSHA, cacheKey string, opContextSrc operationContextSrc, q *apiclient.ManifestRequest) *ManifestResponsePromise {<br>	responseCh := make(chan *apiclient.ManifestResponse)<br>	tarDoneCh := make(chan bool)<br>	errCh := make(chan error)<br>	responsePromise := NewManifestResponsePromise(responseCh, tarDoneCh, errCh)<br><br>	// ✅ 채널 생성 후 고루틴으로 runManifestGenAsync 호출<br>	channels := &amp;generateManifestCh{<br>		responseCh: responseCh,<br>		tarDoneCh:  tarDoneCh,<br>		errCh:      errCh,<br>	}<br>	go s.runManifestGenAsync(ctx, repoRoot, commitSHA, cacheKey, opContextSrc, q, channels)<br>	return responsePromise<br>}<br><br>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/reposerver/repository/repository.go#L701&gt;<br>func (s *Service) runManifestGenAsync(ctx context.Context, repoRoot, commitSHA, cacheKey string, opContextSrc operationContextSrc, q *apiclient.ManifestRequest, ch *generateManifestCh) {<br>	<br>	// ...<br>	<br>	if err == nil {<br><br>		// 분석 용이를 위해 multiple source가 아닌 경우를 가정<br>		if q.HasMultipleSources {<br>			// ...<br>		}<br>	<br>		// ...<br>	<br>		// ✅ manifestGenResult 생성<br>		manifestGenResult, err = GenerateManifests(ctx, opContext.appPath, repoRoot, commitSHA, q, false, s.gitCredsStore, s.initConstants.MaxCombinedDirectoryManifestsSize, s.gitRepoPaths, WithCMPTarDoneChannel(ch.tarDoneCh), WithCMPTarExcludedGlobs(s.initConstants.CMPTarExcludedGlobs))<br>	}<br>	<br>	// ...<br>	<br>	// ✅ cache에 manifest 업데이트<br>	err = s.cache.SetManifests(cacheKey, appSourceCopy, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, &amp;manifestGenCacheEntry, refSourceCommitSHAs, q.InstallationID)<br>	<br>	// ...<br>	<br>	// ✅ 동작 결과 responseCh로 주입<br>	ch.responseCh &lt;- manifestGenCacheEntry.ManifestResponse<br>}</pre><p>runManifestGen은 runManifestGenAsync를 고루틴으로 호출하고 runManifestGenAsync는 다시 GenerateManifests를 호출하여 결과를 캐시에 저장하고 채널로 리턴합니다.</p><p>그럼 실제적으로 manifest를 구성하는 과정은 GenerateManifests에서 발생하는 것을 알 수 있습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/reposerver/repository/repository.go#L1410&gt;<br>func GenerateManifests(ctx context.Context, appPath, repoRoot, revision string, q *apiclient.ManifestRequest, isLocal bool, gitCredsStore git.CredsStore, maxCombinedManifestQuantity resource.Quantity, gitRepoPaths io.TempPaths, opts ...GenerateManifestOpt) (*apiclient.ManifestResponse, error) {<br>	opt := newGenerateManifestOpt(opts...)<br>	var targetObjs []*unstructured.Unstructured<br><br>	// ...<br><br>	// ✅ app source type 조회<br>	appSourceType, err := GetAppSourceType(ctx, q.ApplicationSource, appPath, repoRoot, q.AppName, q.EnabledSourceTypes, opt.cmpTarExcludedGlobs, env.Environ())<br>	<br>	// ...<br>	<br>	var commands []string<br>	<br>	switch appSourceType {<br>	// ✅ helm인 경우<br>	case v1alpha1.ApplicationSourceTypeHelm:<br>		var command string<br>		// ✅ helm template으로부터 targetObjs 생성<br>		targetObjs, command, err = helmTemplate(appPath, repoRoot, env, q, isLocal, gitRepoPaths)<br>		commands = append(commands, command)<br>	// ✅ kustomize인 경우<br>	case v1alpha1.ApplicationSourceTypeKustomize:<br>		// ✅ kustomize binary 등록<br>		kustomizeBinary := &quot;&quot;<br>		if q.KustomizeOptions != nil {<br>			kustomizeBinary = q.KustomizeOptions.BinaryPath<br>		}<br>		// ✅ kustomize를 통해 targetObjs 생성<br>		k := kustomize.NewKustomizeApp(repoRoot, appPath, q.Repo.GetGitCreds(gitCredsStore), repoURL, kustomizeBinary, q.Repo.Proxy, q.Repo.NoProxy)<br>		targetObjs, _, commands, err = k.Build(q.ApplicationSource.Kustomize, q.KustomizeOptions, env, &amp;kustomize.BuildOpts{<br>			KubeVersion: text.SemVer(q.ApplicationSource.GetKubeVersionOrDefault(q.KubeVersion)),<br>			APIVersions: q.ApplicationSource.GetAPIVersionsOrDefault(q.ApiVersions),<br>		})<br>		// ✅ plugin인 경우<br>	case v1alpha1.ApplicationSourceTypePlugin:<br>		// ✅ plugin 등록<br>		pluginName := &quot;&quot;<br>		if q.ApplicationSource.Plugin != nil {<br>			pluginName = q.ApplicationSource.Plugin.Name<br>		}<br>		// if pluginName is provided it has to be `&lt;metadata.name&gt;-&lt;spec.version&gt;` or just `&lt;metadata.name&gt;` if plugin version is empty<br>		// ✅ plugin sidecar로? 실행하여 targetObjs 생성<br>		targetObjs, err = runConfigManagementPluginSidecars(ctx, appPath, repoRoot, pluginName, env, q, opt.cmpTarDoneCh, opt.cmpTarExcludedGlobs)<br>		if err != nil {<br>			err = fmt.Errorf(&quot;plugin sidecar failed. %s&quot;, err.Error())<br>		}<br>	case v1alpha1.ApplicationSourceTypeDirectory:<br>		// ✅ binary인 경우 findManifests로 targetObjs 생성<br>		var directory *v1alpha1.ApplicationSourceDirectory<br>		if directory = q.ApplicationSource.Directory; directory == nil {<br>			directory = &amp;v1alpha1.ApplicationSourceDirectory{}<br>		}<br>		logCtx := log.WithField(&quot;application&quot;, q.AppName)<br>		targetObjs, err = findManifests(logCtx, appPath, repoRoot, env, *directory, q.EnabledSourceTypes, maxCombinedManifestQuantity)<br>	}<br>	<br>	// ...<br><br>	manifests := make([]string, 0)<br>	for _, obj := range targetObjs {<br>		// ✅ targetObjs를 순회하면서 리소스 타입을 json string으로 변경<br>	}<br><br>	return &amp;apiclient.ManifestResponse{<br>		Manifests:  manifests,<br>		SourceType: string(appSourceType),<br>		Commands:   commands,<br>	}, nil<br>}</pre><p>해당 함수 내부에서 source 타입에 따라 맞는 방법으로 manifest를 생성합니다. GenerateManifests에서 manifest가 리턴되면 promise의 responseCh에 manifest가 등록됩니다. 최종으로 promise에서 select대기하는 operation 클로저에 리턴이 수신되고 grpc 요청이 종료됩니다.</p><p>참고자료</p><p><a href="https://argo-cd.readthedocs.io/en/stable/operator-manual/server-commands/argocd-repo-server/">argocd-repo-server Command Reference - Argo CD - Declarative GitOps CD for Kubernetes</a></p><p>참고자료</p><p><a href="https://argo-cd.readthedocs.io/en/stable/operator-manual/server-commands/argocd-repo-server/">argocd-repo-server Command Reference - Argo CD - Declarative GitOps CD for Kubernetes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2867a004fa8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[argocd 분석: app controller의 gitops 구현]]></title>
            <link>https://medium.com/@hyper201286/argocd-%EB%B6%84%EC%84%9D-app-controller%EC%9D%98-gitops-%EA%B5%AC%ED%98%84-55fa7c5fe820?source=rss-619cbfeff5b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/55fa7c5fe820</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[flangdu]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 08:56:52 GMT</pubDate>
            <atom:updated>2024-12-20T08:56:52.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*bO3GF_tJsJAM1--dUqiJmw.png" /></figure><p>application controller에서 application에 대한 이벤트를 informer가 수신하여 CUD에 대한 연산을 큐로 넘기고 ~~~QueueItem()함수가 비동기로 처리하는 부분까지 확인했습니다. App이 새로 추가된 경우, informer의 AddFunc이 호출되고 생성된 object에 대한 key를 다른 고루틴으로 넘겨 처리합니다. 이 고루틴은 processAppRefreshQueueItem 함수를 실행합니다. 이번 아티클에서 processAppRefreshQueueItem이 함수 내부를 탐색해보겠습니다.</p><h3>processAppRefreshQueueItem 내부</h3><p>processAppRefreshQueueItem은 CUD에 대한 연산이 수행된 app을 비동기로 처리하는 최상위 함수입니다. 이 함수가 수행하는 동작이 많지만 app 생성 과정에서 크게 요약해보면 다음과 같이 작업이 이루어집니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/appcontroller.go#L1541&gt;<br>func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext bool) {<br>	<br>	// ...<br>	<br>	// ✅ queue에 삽입된 원소를 구독<br>	appKey, shutdown := ctrl.appRefreshQueue.Get()<br>	<br>	// ...<br>	<br>	// ✅ 1. app 상태가 refresh가 필요한 상태인지 검증<br>	needRefresh, refreshType, comparisonLevel := ctrl.needRefreshAppStatus(origApp, ctrl.statusRefreshTimeout, ctrl.statusHardRefreshTimeout)<br>	<br>	// ... <br>	<br>	// ✅ 2. project 조회 및 spec 검증<br>	project, hasErrors := ctrl.refreshAppConditions(app)<br>	<br>	// ...<br>	<br>	// ✅ 3. app 상태 비교<br>	compareResult, err := ctrl.appStateManager.CompareAppState(app, project, revisions, sources,<br>		refreshType == appv1.RefreshTypeHard,<br>		comparisonLevel == CompareWithLatestForceResolve, localManifests, hasMultipleSources, false)<br>		<br>	// ...<br>	<br>	// ✅ 4. app에 대한 tree 생성 및 summary 작성<br>	tree, err := ctrl.setAppManagedResources(app, compareResult)<br>	<br>	// ...<br>	<br>	// ✅ 5. sync 가능 상태에 따라 autosync<br>	canSync, _ := project.Spec.SyncWindows.Matches(app).CanSync(false)<br>	if canSync {<br>		syncErrCond, opMS := ctrl.autoSync(app, compareResult.syncStatus, compareResult.resources, compareResult.revisionUpdated)<br>		// ...<br>	}<br>	<br>	// ...<br>	// app 상태 갱신 및 마무리<br>}</pre><p>가장 먼저 queue에서 원소를 가져옵니다. queue에서 원소를 가져온 이후 단계는 크게 다섯 단계로 구분할 수 있습니다.</p><ol><li>app 상태가 refresh가 필요한지 검증합니다. 강제 or 일반 refresh와 리소스를 어떻게 동기화할지 레벨을 결정합니다.</li><li>project 조회 및 app spec 검증합니다. app의 형식이 argocd에 포함된 클러스터인지 원격 저장소는 접근 가능한지 여부를 검증합니다.</li><li>app 상태 비교: 가장 중요한 부분으로 원격 저장소의 상태와 k8s로 관리되는 app의 리소스를 비교하는 과정을 수행합니다.</li><li>app에 대한 tree를 생성하고 app summary를 작성합니다.</li><li>sync가능 여부에 따라 autosync를 활성화합니다.</li></ol><p>processAppRefreshQueueItem 내부에서 가장 중요한 부분은 3번째 과정인 app 상태를 비교하는 부분입니다. ctrl.appStateManager.CompareAppState 함수로 argocd에서 실질적인 gitops가 구현됩니다. 그럼 ctrl.appStateManager.CompareAppState내부를 살펴보겠습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/state.go#L429&gt;<br>func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1alpha1.AppProject, revisions []string, sources []v1alpha1.ApplicationSource, noCache bool, noRevisionCache bool, localManifests []string, hasMultipleSources bool, rollback bool) (*comparisonResult, error) {<br><br>	// ...<br><br>	<br>	if len(localManifests) == 0 {<br><br>		// ...<br>		<br>		// ✅ 1. 원격 저장소에서 대상 object 조회<br>		targetObjs, manifestInfos, revisionUpdated, err = m.GetRepoObjs(app, sources, appLabelKey, revisions, noCache, noRevisionCache, verifySignature, project, rollback)<br>		<br>		// ...<br>	<br>	}<br><br>	// ...<br>	<br>	//  ✅ 2. 중복 오브젝트 제거<br>	targetObjs, dedupConditions, err := DeduplicateTargetObjects(app.Spec.Destination.Namespace, targetObjs, infoProvider)<br>	<br>	// ...<br><br>	// ✅ 3. 대상 클러스터에 배포된 object 조회<br>	liveObjByKey, err := m.liveStateCache.GetManagedLiveObjs(app, targetObjs)<br>	<br>	// ...<br>	<br>	// 4. ✅ 재조정 대상 오브젝트 조회<br>	reconciliation := sync.Reconcile(targetObjs, liveObjByKey, app.Spec.Destination.Namespace, infoProvider)<br>	<br>	// ...<br>	<br>	// 5. ✅ diff config 설정 및 diff 결과 가져옴<br>	diffResults, err := argodiff.StateDiffs(reconciliation.Live, reconciliation.Target, diffConfig)<br>	<br>	// ...<br>	<br>	// 6. ✅ 리소스 순회하며 managedResources, resourcesSummaries 필드 생성<br>	managedResources := make([]managedResource, len(reconciliation.Target))<br>	resourceSummaries := make([]v1alpha1.ResourceStatus, len(reconciliation.Target))<br>	for i, targetObj := range reconciliation.Target {<br>		<br>		// ...<br>	<br>		if liveObj != nil {<br>			resourceVersion = liveObj.GetResourceVersion()<br>		}<br>		managedResources[i] = managedResource{<br>			Name:            resState.Name,<br>			Namespace:       resState.Namespace,<br>			Group:           resState.Group,<br>			Kind:            resState.Kind,<br>			Version:         resState.Version,<br>			Live:            liveObj,<br>			Target:          targetObj,<br>			Diff:            diffResult,<br>			Hook:            resState.Hook,<br>			ResourceVersion: resourceVersion,<br>		}<br>		resourceSummaries[i] = resState<br>	}<br>	<br>	// ...<br><br>	compRes := comparisonResult{<br>		syncStatus:           &amp;syncStatus,<br>		healthStatus:         healthStatus,<br>		resources:            resourceSummaries,<br>		managedResources:     managedResources,<br>		reconciliationResult: reconciliation,<br>		diffConfig:           diffConfig,<br>		diffResultList:       diffResults,<br>		hasPostDeleteHooks:   hasPostDeleteHooks,<br>		revisionUpdated:      revisionUpdated,<br>	}<br>	<br>	// ...<br>	<br>	return &amp;compRes, nil<br>}</pre><p>함수 동작을 요약하면 다음과 같습니다.</p><ul><li>원격 저장소에 있는 오브젝트 목록을 가져옵니다.</li><li>현재 배포 상태를 조회합니다.</li><li>재조정할 대상 오브젝트를 조회합니다.</li><li>diff 범위를 설정합니다.</li><li>리소스를 순회하면서 상태를 비교합니다.</li></ul><p>이 동작은 테스트 코드를 통해 확인이 가능합니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/state_test.go#L481&gt;<br>// TestAppRevisions tests that revisions are properly propagated for a single source app<br>func TestAppRevisionsSingleSource(t *testing.T) {<br>	obj1 := NewPod()<br>	obj1.SetNamespace(test.FakeDestNamespace)<br>	data := fakeData{<br>		// ✅ 원격 저장소에 존재하는 object: 파드를 하나 배포해야 함<br>		manifestResponse: &amp;apiclient.ManifestResponse{<br>			Manifests: []string{toJSON(t, obj1)},<br>			Namespace: test.FakeDestNamespace,<br>			Server:    test.FakeClusterURL,<br>			Revision:  &quot;abc123&quot;,<br>		},<br>		// ✅ k8s 대상 클러스터에 배포된 리소스: map에 아무 원소 없음<br>		managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),<br>	}<br>	ctrl := newFakeController(&amp;data, nil)<br><br>	app := newFakeApp()<br>	revisions := make([]string, 0)<br>	revisions = append(revisions, &quot;&quot;)<br>	compRes, err := ctrl.appStateManager.CompareAppState(app, &amp;defaultProj, revisions, app.Spec.GetSources(), false, false, nil, app.Spec.HasMultipleSources(), false)<br>	// 통과 조건<br>	require.NoError(t, err)<br>	assert.NotNil(t, compRes)<br>	assert.NotNil(t, compRes.syncStatus)<br>	assert.NotEmpty(t, compRes.syncStatus.Revision)<br>	assert.Empty(t, compRes.syncStatus.Revisions)<br>}</pre><p>위의 테스트 로직을 추적해보면 다음과 같이 동작합니다.</p><ol><li>CompareAppState 의 ✅ 1번에서 targetObjs에 pod가 하나 포함됩니다. 또한 manifestInfos.Manifests 배열에 manifest가 string 형식으로 저장됩니다.</li><li>중복 오브젝트는 건너뜁니다.</li><li>✅ 3번에서 liveObjByKey로 배포된 오브젝트를 가져오지만 아무것도 조회되지 않습니다.</li><li>✅ 4번에서 재조정 대상 오브젝트를 조회합니다. 이때 reconciliation에는 Live와 Target을 배열로 소유하는데, Live는 현재 배포된 상태, Target은 배포할 상태를 의미합니다. Live는 nil을 가지고 Target에는 파드를 가집니다.</li><li>✅ 5번에서 diff결과를 만듭니다. DiffResults에는 reconciliation처럼 live와 target에 대한 정보를 string manifest로 소유합니다.</li></ol><p>test코드는 vscode에서 다음처럼 왼쪽 초록색 버튼으로 쉽게 디버깅이 가능합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*tL2BL1YWYJil2pe8rxM8kg.png" /></figure><p>좀 더 복잡한 테스트를 확인하고 싶으면 TestCompareAppStateDuplicatedNamespacedResources가 좋은 예시가 되겠습니다.</p><p>이렇게 k8s에 app 오브젝트가 생성되어 informer로 이벤트를 받아 queue로 처리하고 CompareAppState함수로 오브젝트 상태를 파악하는 과정을 거쳤습니다. CompareAppState함수 내부에서 원격 저장소 상태와 클러스터 상태를 비교하여 원하는 상태를 확인하는 과정을 살펴봤습니다. 그러나 아직 살펴보지 않은 부분이 두 부분이 있습니다. 첫 번째는 repository server와 상호작용이고, 하나는 k8s 리소스에 대한 생성입니다. 다음에는 repository server와 상호작용하는 부분을 찾아보겠습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55fa7c5fe820" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[argocd 분석: app controller의 app 상태 변화 감지]]></title>
            <link>https://medium.com/@hyper201286/argocd-%EB%B6%84%EC%84%9D-app-controller%EC%9D%98-app-%EC%83%81%ED%83%9C-%EB%B3%80%ED%99%94-%EA%B0%90%EC%A7%80-5a479c864e2e?source=rss-619cbfeff5b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a479c864e2e</guid>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[kubernetes-operator]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[flangdu]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 13:31:15 GMT</pubDate>
            <atom:updated>2024-12-18T13:31:15.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*bO3GF_tJsJAM1--dUqiJmw.png" /></figure><p>app이 api server로부터 생성되는 것을 확인했습니다. 이번에는 app 생성이 argocd에서 어떻게 감지되는지 찾아보겠습니다. 이번에는 application controller 코드를 다룹니다.</p><h3>application controller의 시작점</h3><p>이번도 마찬가지로 같은 main에서 출발합니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/cmd/main.go#L27&gt;<br>func main() {<br>	var command *cobra.Command // ✅ cobra command 생성<br><br>	// ✅ 실행하는 바이너리 이름 가져오기<br>	binaryName := filepath.Base(os.Args[0])<br>	if val := os.Getenv(binaryNameEnv); val != &quot;&quot; {<br>		binaryName = val<br>	}<br><br>	// ✅ 바이너리 이름에 따라 실행할 대상 매칭<br>	isCLI := false<br>	switch binaryName {<br>	// ...<br>	// ✅ application controller인 경우 case 매칭<br>	case &quot;argocd-application-controller&quot;:<br>		command = appcontroller.NewCommand()<br>	// ...<br>}</pre><p>지금까지 그랬던 것처럼 Run메서드를 확인해보겠습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/cmd/argocd-application-controller/commands/argocd_application_controller.go#L95&gt;<br>		RunE: func(c *cobra.Command, args []string) error {<br>			<br>			// log 포멧 등 설정 초기화 ...<br>			// ...<br><br>			// ✅ appController 생성<br>			appController, err = controller.NewApplicationController(<br>				// ...<br>			)<br>			<br>			// ...<br><br>			// ✅ appController 실행<br>			go appController.Run(ctx, statusProcessors, operationProcessors)<br><br>			// ...<br>		},</pre><p>핵심은 api server와 비슷합니다. 설정 초기화 → 실행 → 종료 대기 순서를 따르고 있습니다.</p><p>여기서 생성자인 controller.NewApplicationController 함수를 살펴보겠습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/appcontroller.go#L152&gt;<br>func NewApplicationController(<br><br>	// 설정 ...<br>	<br>) (*ApplicationController, error) {<br><br>	// ...<br><br>	ctrl := ApplicationController{<br>		// ...<br>	}<br>	<br>	// ...<br>	<br>	// ✅ 주요 지점!<br>	appInformer, appLister := ctrl.newApplicationInformerAndLister()<br>	<br>	// ...<br>	<br>}</pre><p>이 함수는 *ApplicationController필드를 초기화하고 필요한 데이터를 세팅하는 부분입니다. 이때 주요 지점으로 appInformer, appLister := ctrl.newApplicationInformerAndLister() 가 있습니다.</p><p>k8s operator를 분석할 때 가장 주요한 지점 중 하나는 위와 같은 ~~~informer를 확인하는 것입니다. informer는 <strong>k8s 객체의 변화를 감지하여 런타임에 알려주는 역할을 수행</strong>합니다. 따라서 appInformer라는 대상은 argocd application 객체에 대한 변화를 런타임에 알려줄 것이라고 추측할 수 있습니다.</p><p>이번에는 appInformer를 생성하는 코드 내부를 확인해봅시다. appInformer, appLister := ctrl.newApplicationInformerAndLister() 이 코드 내부에 app이 변화했을 때 호출되는 함수가 존재합니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/appcontroller.go#L2188C1-L2188C129&gt;<br>func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.SharedIndexInformer, applisters.ApplicationLister) {<br>	<br>	// ...<br>	<br>	// informer 생성<br>	informer := cache.NewSharedIndexInformer( ... )<br>	<br>	// ...<br>	<br>	// informer callback함수 업데이트<br>	_, err := informer.AddEventHandler(<br>		cache.ResourceEventHandlerFuncs{<br>			AddFunc: func(obj interface{}) {<br>			<br>				// ...<br>				<br>			UpdateFunc: func(old, new interface{}) {<br>			<br>				// ...<br>				<br>			DeleteFunc: func(obj interface{}) {<br>			<br>				// ...<br>				<br>			},<br>		},<br>	)<br>}</pre><p>newApplicationInformerAndLister() 내부에서 informer가 생성되고 informer의 AddEventHandler를 이용하여 event 발생 시 호출되는 callback을 주입받습니다. 이때 AddFunc, UpdateFunc, DeleteFunc이 추가되는데, 각각 관찰하려는 대상 객체에 대한 이벤트 생성, 수정, 삭제에 대한 callback을 의미합니다.</p><p>각 callback 코드를 살펴보겠습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/appcontroller.go#L2274&gt;<br>	AddFunc: func(obj interface{}) {<br>	<br>		// ...<br>		<br>		// ✅ obj에 대한 key 조회<br>		key, err := cache.MetaNamespaceKeyFunc(obj)<br>		if err == nil {<br>			// ✅ 에러가 없는 경우만 appRefreshQueue에 삽입<br>			// 채널에 key 추가<br>			ctrl.appRefreshQueue.AddRateLimited(key)<br>		}<br>		<br>		// ...<br>	<br>	},<br>	UpdateFunc: func(old, new interface{}) {<br>		<br>		// ...<br>		<br>		// ✅ obj에 대한 key 조회<br>		key, err := cache.MetaNamespaceKeyFunc(new)<br>		if err != nil {<br>			return<br>		}<br>		<br>		// ...<br><br>		oldApp, oldOK := old.(*appv1.Application)<br>		newApp, newOK := new.(*appv1.Application)<br>		<br>		// ...<br><br>		// ✅ appRefreshQueue에 삽입<br>		ctrl.requestAppRefresh(newApp.QualifiedName(), compareWith, delay)<br>		<br>		// ...<br>	},<br>	DeleteFunc: func(obj interface{}) {<br>	<br>		// ...<br>	<br>		key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)<br>		if err == nil {<br>			<br>			// ...<br>			<br>			// ✅ delete 또한 appRefreshQueue에 삽입<br>			ctrl.appRefreshQueue.Add(key)<br>		}<br>		<br>		// ...<br><br>	},</pre><p>코드의 흐름은 거의 비슷합니다. CUD에 대한 app 변경 사항이 있을 때마다 appRefreshQueue에 key를 삽입합니다. appRefreshQueue 내부는 golang의 기본적인 channel을 이용하여 pub sub으로 동작합니다.</p><p>그럼 appRefreshQueue에 원소를 가져가는 부분은 어디일까요?</p><p>이 부분은 처음 확인했던 부분에서 Run을 봐야합니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/cmd/argocd-application-controller/commands/argocd_application_controller.go#L95&gt;<br>		RunE: func(c *cobra.Command, args []string) error {<br>		<br>			// ...<br>		<br>			// ✅ appController 실행<br>			go appController.Run(ctx, statusProcessors, operationProcessors)<br><br>			// ...<br>		},</pre><h3>appController.Run 내부</h3><p>이번에는 실행하는 부분의 내부를 살펴보겠습니다.</p><pre>// &lt;https://github.com/argoproj/argo-cd/blob/079754c63913522803f7dbe4bded6b6de37f7e34/controller/appcontroller.go#L836&gt;<br>func (ctrl *ApplicationController) Run(ctx context.Context, statusProcessors int, operationProcessors int) {<br><br>	// ...<br><br>	// ✅ 앞서 callback함수를 등록한 Informer의 실행<br>	go ctrl.appInformer.Run(ctx.Done())<br>	go ctrl.projInformer.Run(ctx.Done())<br><br>	// ...<br><br>	// ✅ refresh queue, operation queue, app comparison type queue, project queue 실행<br>	for i := 0; i &lt; statusProcessors; i++ {<br>		go wait.Until(func() {<br>			for ctrl.processAppRefreshQueueItem() {<br>			}<br>		}, time.Second, ctx.Done())<br>	}<br><br>	for i := 0; i &lt; operationProcessors; i++ {<br>		go wait.Until(func() {<br>			for ctrl.processAppOperationQueueItem() {<br>			}<br>		}, time.Second, ctx.Done())<br>	}<br><br>	go wait.Until(func() {<br>		for ctrl.processAppComparisonTypeQueueItem() {<br>		}<br>	}, time.Second, ctx.Done())<br><br>	go wait.Until(func() {<br>		for ctrl.processProjectQueueItem() {<br>		}<br>	}, time.Second, ctx.Done())<br>	&lt;-ctx.Done()<br>}</pre><p>Run함수의 구현은 크게 다음과 같이 나눠집니다.</p><ol><li>informer 실행</li><li>queue subscribe 함수 실행</li></ol><p>먼저 informer를 실행하는 부분은 앞서 appController 생성자에서 확인했던 informer함수를 활성화하는 역할을 수행합니다. Run 메서드를 비동기로 호출하면서 쿠버네티스 이벤트를 감지합니다.</p><p>다음로 queue를 비동기로 실행하여 informer에서 전달되는 이벤트를 구독합니다. queue의 구독 함수에서 동작에 알맞는 행동을 수행합니다.</p><p>지금까지 과정을 다이어그램으로 나타내면 다음과 같이 표현할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PgYb-ASCOddttvmwf9SRQ.png" /></figure><p>확인한 코드에서 중요한 부분은 여러 고루틴으로 실행하는 ctrl.processAppRefreshQueueItem() 과 ctrl.processAppOperationQueueItem() 입니다. 다음 아티클에서 비동기로 실행되는 queue 이벤트 구독 함수에서 어떤 일이 일어나는지 확인해보겠습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a479c864e2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>