Ubuntu install on M1

개요

  • M1에서 Ubuntu를 설치하는 방법에 대해 기술한다.

Ubuntu 24.04 LTS 다운로드

  • Ubuntu Download를 진행한다.
    • 다운로드 받을 시, arm으로 다운로드 받아야 한다.
    • 다른 아키텍처로 다운로드 받을 시 리눅스가 활성화가 되지 않는다.
  • 사이트 : https://ubuntu.com/download/server/arm

Screenshot 2024-05-21 at 9.43.12 AM.png

Screenshot 2024-05-21 at 10.46.43 AM.png

UTM 다운로드

Screenshot 2024-05-21 at 9.29.15 AM.png

UTM 가상머신 생성

  • UTM을 실행하면 아래와 같은 화면이 나온다.
  • Create a New Virtual Machine을 선택한다.

Screenshot 2024-05-21 at 9.30.52 AM.png

gcloud installation on Mac, SSH Connection with VSCode

개요

Screenshot 2024-04-22 at 6.15.48 PM.png

설치파일 다운로드

  • 각 사용자 버전에 맞는 설치 파일을 다운로드 받는다.
    • 필자는 M1 silicon 버전을 사용하기로 하였다.
    • Desktop > gcloud_install 내부에 해당 파일을 다운로드 받았다.

Screenshot 2024-04-22 at 6.16.45 PM.png

  • 압축을 풀면 아래와 같이 google-cloud-sdk 폴더 안애 install.sh 파일이 있다.

Screenshot 2024-04-22 at 6.20.54 PM.png

설치파일 실행

  • 해당 폴더에 있는 파일에 접속해서 install.sh 파일을 실행한다.
$ {your_location}/google-cloud-sdk/install.sh
Welcome to the Google Cloud CLI!

To help improve the quality of this product, we collect anonymized usage data
and anonymized stacktraces when crashes are encountered; additional information
is available at <https://cloud.google.com/sdk/usage-statistics>. This data is
handled in accordance with our privacy policy
<https://cloud.google.com/terms/cloud-privacy-notice>. You may choose to opt in this
collection now (by choosing 'Y' at the below prompt), or at any time in the
future by running the following command:

    gcloud config set disable_usage_reporting false

Do you want to help improve the Google Cloud CLI (y/N)? y

Your current Google Cloud CLI version is: 471.0.0
The latest available version is: 472.0.0

┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                     Components                                                     │
├──────────────────┬──────────────────────────────────────────────────────┬──────────────────────────────┬───────────┤
│      Status      │                         Name                         │              ID              │    Size   │
├──────────────────┼──────────────────────────────────────────────────────┼──────────────────────────────┼───────────┤
│ Update Available │ BigQuery Command Line Tool                           │ bq                           │   1.7 MiB │
│ Update Available │ Google Cloud CLI Core Libraries                      │ core                         │  18.4 MiB │
│ Not Installed    │ App Engine Go Extensions                             │ app-engine-go                │   4.5 MiB │
│ Not Installed    │ Appctl                                               │ appctl                       │  18.5 MiB │
│ Not Installed    │ Artifact Registry Go Module Package Helper           │ package-go-module            │   < 1 MiB │
│ Not Installed    │ Cloud Bigtable Command Line Tool                     │ cbt                          │  16.7 MiB │
│ Not Installed    │ Cloud Bigtable Emulator                              │ bigtable                     │   7.0 MiB │
│ Not Installed    │ Cloud Datastore Emulator                             │ cloud-datastore-emulator     │  36.2 MiB │
│ Not Installed    │ Cloud Firestore Emulator                             │ cloud-firestore-emulator     │  44.8 MiB │
│ Not Installed    │ Cloud Pub/Sub Emulator                               │ pubsub-emulator              │  63.3 MiB │
│ Not Installed    │ Cloud Run Proxy                                      │ cloud-run-proxy              │  11.3 MiB │
│ Not Installed    │ Cloud SQL Proxy v2                                   │ cloud-sql-proxy              │  13.2 MiB │
│ Not Installed    │ Google Container Registry's Docker credential helper │ docker-credential-gcr        │           │
│ Not Installed    │ Kustomize                                            │ kustomize                    │   7.4 MiB │
│ Not Installed    │ Log Streaming                                        │ log-streaming                │  11.9 MiB │
│ Not Installed    │ Minikube                                             │ minikube                     │  33.6 MiB │
│ Not Installed    │ Nomos CLI                                            │ nomos                        │  28.6 MiB │
│ Not Installed    │ On-Demand Scanning API extraction helper             │ local-extract                │  13.7 MiB │
│ Not Installed    │ Skaffold                                             │ skaffold                     │  22.8 MiB │
│ Not Installed    │ Terraform Tools                                      │ terraform-tools              │  63.6 MiB │
│ Not Installed    │ anthos-auth                                          │ anthos-auth                  │  20.7 MiB │
│ Not Installed    │ config-connector                                     │ config-connector             │  55.6 MiB │
│ Not Installed    │ enterprise-certificate-proxy                         │ enterprise-certificate-proxy │   8.3 MiB │
│ Not Installed    │ gcloud Alpha Commands                                │ alpha                        │   < 1 MiB │
│ Not Installed    │ gcloud Beta Commands                                 │ beta                         │   < 1 MiB │
│ Not Installed    │ gcloud app Java Extensions                           │ app-engine-java              │ 126.2 MiB │
│ Not Installed    │ gcloud app PHP Extensions                            │ app-engine-php               │  21.9 MiB │
│ Not Installed    │ gcloud app Python Extensions                         │ app-engine-python            │   5.0 MiB │
│ Not Installed    │ gcloud app Python Extensions (Extra Libraries)       │ app-engine-python-extras     │   < 1 MiB │
│ Not Installed    │ gke-gcloud-auth-plugin                               │ gke-gcloud-auth-plugin       │   7.4 MiB │
│ Not Installed    │ kpt                                                  │ kpt                          │  14.4 MiB │
│ Not Installed    │ kubectl                                              │ kubectl                      │   < 1 MiB │
│ Not Installed    │ kubectl-oidc                                         │ kubectl-oidc                 │  20.7 MiB │
│ Not Installed    │ pkg                                                  │ pkg                          │           │
│ Installed        │ Cloud Storage Command Line Tool                      │ gsutil                       │  11.3 MiB │
│ Installed        │ Google Cloud CRC32C Hash Tool                        │ gcloud-crc32c                │   1.2 MiB │
└──────────────────┴──────────────────────────────────────────────────────┴──────────────────────────────┴───────────┘
To install or remove components at your current SDK version [471.0.0], run:
  $ gcloud components install COMPONENT_ID
  $ gcloud components remove COMPONENT_ID

To update your SDK installation to the latest version [472.0.0], run:
  $ gcloud components update

Modify profile to update your $PATH and enable shell command completion?

Do you want to continue (Y/n)?  y

The Google Cloud SDK installer will now prompt you to update an rc file to bring
 the Google Cloud CLIs into your environment.

Enter a path to an rc file to update, or leave blank to use 
[/Users/evan/.bash_profile]:  
Backing up [/Users/evan/.bash_profile] to [/Users/evan/.bash_profile.backup].
[/Users/evan/.bash_profile] has been updated.

==> Start a new shell for the changes to take effect.

Google Cloud CLI works best with Python 3.11 and certain modules.

Download and run Python 3.11 installer? (Y/n)?  Y
Running Python 3.11 installer, you may be prompted for sudo password...
Password: # your_password
installer: Package name is Python
installer: Upgrading at base path /
installer: The upgrade was successful.
Setting up virtual environment
Creating virtualenv...
Installing modules...
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 89.7/89.7 kB 4.6 MB/s eta 0:00:00
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 59.0/59.0 kB 5.9 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10.0/10.0 MB 33.9 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 163.8/163.8 kB 16.1 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 5.3/5.3 MB 42.0 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 176.7/176.7 kB 15.4 MB/s eta 0:00:00
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 117.6/117.6 kB 10.4 MB/s eta 0:00:00
  Building wheel for crcmod (pyproject.toml) ... done

Updates are available for some Google Cloud CLI components.  To install them,
please run:
  $ gcloud components update

Virtual env enabled.

For more information on how to get started, please visit:
  https://cloud.google.com/sdk/docs/quickstarts
  • gcloud CLI를 초기화하려면 gcloud init 을 실행한다.
$ ./google-cloud-sdk/bin/gcloud init
Welcome! This command will take you through the configuration of gcloud.

Your current configuration has been set to: [default]

You can skip diagnostics next time by using the following flag:
  gcloud init --skip-diagnostics

Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.                                            
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

You must log in to continue. Would you like to log in (Y/n)?  Y

Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/....S256

You are logged in as: [your_email@gmail.com].

Pick cloud project to use: 
 [1] chickenbot-a185e
 [2] encoded-phalanx-420600
 [3] streamlit-gitaction-403105
 [4] streamlit-project-416601
 [5] Enter a project ID
 [6] Create a new project
Please enter numeric choice or text value (must exactly match list item):  2

Screenshot 2024-04-22 at 6.34.04 PM.png

gcloud Installation on Windows 11 - New Configuration

개요

재설치

  • 재설치의 마지막 화면은 다음과 같다.
  • Pick configuration to use, Section에서 2번을 선택한다.

Untitled

  • 이후 CMD 화면이 팝업화가 된다.
Welcome to the Google Cloud CLI! Run "gcloud -h" to get the list of available commands.
---
Welcome! This command will take you through the configuration of gcloud.

Settings from your current configuration [default] are:
accessibility:
  screen_reader: 'True'
compute:
  region: asia-northeast3
  zone: asia-northeast3-a
core:
  account: your_existing@gmail.com
  disable_usage_reporting: 'False'
  project: mulcampfp

Pick configuration to use:
 [1] Re-initialize this configuration [default] with new settings
 [2] Create a new configuration
Please enter your numeric choice:  2
  • 이번에는 Enter configuration name이 있다. 이 때, 접속하고자 하는 [mulcamp-project-abc] 프로젝트를 입력한다.
  • 이 때, 참고하고자 하는 프로젝트 정보에서 Project ID와 매칭되는 것을 선택한다.
Enter configuration name. Names start with a lower case letter and contain only lower case letters a-z, digits 0-9, and
hyphens '-':  mulcamp-project-abc
Your current configuration has been set to: [mulcamp-project-abc]
  • 기존 이메일 주소를 선택하거나 또는 다른 이메일을 선택한다. 필자는 1번으로 선택하였다.
You can skip diagnostics next time by using the following flag:
  gcloud init --skip-diagnostics

Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

Choose the account you would like to use to perform operations for this configuration:
 [1] your_email@gmail.com
 [2] Log in with a new account
Please enter your numeric choice: 1
  • 로그인 이후에는 기존 이메일 계정에 있는 프로젝트 목록이 활성화 될 것이다.

Untitled

Github Actions with GCE, SSH-Key 값 등록

개요

  • Github Actions 강의 중, 애매한 부분을 정리하였다.
  • Github Actions에 대한 전체 코드는 여기에서 다루지는 않는다.

SSH-Key 값 설정

  • GCE에서 Github와 연동을 위해서는 Key값을 생성해야 한다.
  • 본인의 구글클라우드 이메일을 추가하여 아래와 같이 코드를 실행한다.
  • GCP의 ID와 Github의 이메일 주소가 다른 분들이 있다. 이럴 경우 문제가 발생할 수 있다.
    • 주의 : Github 이메일 주소가 아님
$ ssh-keygen -t rsa -b 4096 -C "your@gmail.com"

Github SSH Key값 생성

  • ssh의 public 키값을 복사한다.
$ cat .ssh/id_rsa.pub 
ssh-rsa AAAAB3...Q== your@gmail.com

Github SSH 등록

  • public key값을 복사하여 아래 SSH and GPG keys 값에 복사한다.

Untitled

django-web on GCE

개요

  • django-web을 GCE에 설치 및 배포를 간단하게 진행하도록 한다.

사전준비

  • Google Cloud Platform 회원가입은 미리 진행했고, GCE 인스턴스를 생성할 줄 아는 상태임을 전제로 한다.
  • Miniconda 설치가 끝난 상황임을 가정한다.
  • Miniconda 설치
mkdir -p ~/miniconda3
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda3/miniconda.sh
bash ~/miniconda3/miniconda.sh -b -u -p ~/miniconda3
rm -rf ~/miniconda3/miniconda.sh
  • 설치 후, 새로 설치한 미니콘다를 초기화합니다. 다음 명령은 bash 및 zsh 셸을 초기화
~/miniconda3/bin/conda init bash
~/miniconda3/bin/conda init zsh

django on GCE

  • GCE Shell에서 django를 설치한다.
pip install django
  • django의 버전을 확인한다.
django-admin --version
5.0.4
  • project 명령어를 입력한다.
django-admin startproject mysite
  • 서버를 실행해본다.
    • 경로를 mysite에 이동 시킨 후 아래 명령어를 실행한다.
$ python manage.py makemigrations
$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK
$ python manage.py runserver
...

April 18, 2024 - 05:13:47
Django version 5.0.4, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Untitled

Spark Code 실행 예제

강의소개

개요

  • 현재 러닝 스파크 교재를 배우고 있다.
  • 해당 교재는 주로 00.py에서 실행하는 방법으로 안내하고 있지만, Google Colab에서 어떻게 변환하는지 확인해보고자 한다.

Spark 설정

Untitled

  • Download 버튼을 클릭하면 아래와 같은 화면이 나온다.
    • 주소를 복사한다. https://dlcdn.apache.org/spark/spark-3.5.1/spark-3.5.1-bin-hadoop3.tgz

Untitled

Pandas DataFrame to MySQL Database using iris Data

개요

  • 이전 강의에 이어서 진행한다. (MySQL Select Clause via Python)
  • 임의의 Pandas 데이터 프레임에서 MySQL DB로 추가하는 코드를 작성한다.

주요 라이브러리 설치

  • 아래와 같이 주요 라이브러리를 설치한다.
    • MySQL과 관련된 주요 Python 라이브러리를 설치한다.
pip install mysql-connector mysql-connector-python pymysql SQLAlchemy seaborn pandas

코드 작성(mysql-connector)

  • 아래와 같이 코드를 작성한다.
# 파일명 : db.py
import mysql.connector
import pandas as pd
import seaborn as sns

mydb = mysql.connector.connect(
    host = "localhost", 
    user = "root", 
    passwd = "evan",
    database = "muldb"
)

print(mydb)

iris_df = sns.load_dataset('iris')

my_cursor = mydb.cursor()

create_table_query  = """
   CREATE TABLE IF NOT EXISTS iris (
    id INT AUTO_INCREMENT PRIMARY KEY,
    sepal_length FLOAT,
    sepal_width FLOAT,
    petal_length FLOAT,
    petal_width FLOAT,
    species VARCHAR(255)
    ); 
"""

my_cursor.execute(create_table_query)

insert_query = """
    INSERT INTO iris (sepal_length, sepal_width, petal_length, petal_width, species) 
    VALUES (%s, %s, %s, %s, %s)
"""

data = [tuple(x) for x in iris_df.to_numpy()]

for row in data:
    my_cursor.execute(insert_query, row)

# DB Commit
mydb.commit()

# 종료
my_cursor.close()
mydb.close()
  • 이번에는 Python 파일을 실행한다.
$ python db.py 
<mysql.connector.connection_cext.CMySQLConnection object at 0x0000025FFC155BD0>
  • 이번에는 MySQL Workbench에서 확인한다.

Untitled

MySQL Select Clause via Python

개요

데이터 조회

  • 다음 코드를 작성한다.
import mysql.connector

mydb = mysql.connector.connect(
    host = "localhost", 
    user = "root", 
    passwd = "evan", 
    database = "mulcampdb"
)

print(mydb)

my_cursor = mydb.cursor()

query = """
   SELECT * FROM users;
"""

my_cursor.execute(query)

result = my_cursor.fetchall()
for row in result:
    print(row)
    
print("완료")
  • 파일을 실행한다.
$ python database.py 
<mysql.connector.connection_cext.CMySQLConnection object at 0x000001FE5A985F10>
('Evan', 'Evan@gmail.com', 30, 1)
('Evan', 'Evan@gmail.com', 30, 2)
('Mary', 'Mary@gmail.com', 20, 3)
('Sara', 'Sara@gmail.com', 25, 4)
완료

pandas 데이터프레임으로 변환

  • 주어진 결괏값으로 pandas 데이터프레임으로 변환한다.
  • 먼저 라이브러리를 설치한다.
$ pip install pandas
  • 데이터 같이 코드를 작성한다.
import mysql.connector
import pandas as pd 

mydb = mysql.connector.connect(
    host = "localhost", 
    user = "root", 
    passwd = "evan", 
    database = "mulcampdb"
)

print(mydb)

my_cursor = mydb.cursor(dictionary=True)

query = """
   SELECT * FROM users;
"""

my_cursor.execute(query)

result = my_cursor.fetchall()
for row in result:
    print(row)

df = pd.DataFrame(result)
print(df)
print("완료")
  • 파일을 실행한다.
$ python database.py 
<mysql.connector.connection_cext.CMySQLConnection object at 0x000002C4C47D5490>
{'name': 'Evan', 'email': 'Evan@gmail.com', 'age': 30, 'user_id': 1}
{'name': 'Evan', 'email': 'Evan@gmail.com', 'age': 30, 'user_id': 2}
{'name': 'Mary', 'email': 'Mary@gmail.com', 'age': 20, 'user_id': 3}
{'name': 'Sara', 'email': 'Sara@gmail.com', 'age': 25, 'user_id': 4}
   name           email  age  user_id
0  Evan  Evan@gmail.com   30        1
1  Evan  Evan@gmail.com   30        2
2  Mary  Mary@gmail.com   20        3
3  Sara  Sara@gmail.com   25        4
완료

코드 복기

  • 커서를 생성하는 코드를 다시 확인해본다.
    • 이 코드는 dictionary=True는 조회 결과를 Dictionary 형태로 받기 위한 설정이다.
my_cursor = mydb.cursor(dictionary=True)
  • 이 코드로 인해, pandas DataFrame으로 변환하는 것이 매우 쉬워진다.
result = my_cursor.fetchall()
df = pd.DataFrame(result)
print(df)

MySQL Table Creation and Insert Data via Python

개요

테이블 생성

  • 아래 코드를 작성하면 테이블이 생성된다.
import mysql.connector

mydb = mysql.connector.connect(
    host = "localhost", 
    user = "root", 
    passwd = "evan", 
    database = "mulcampdb"
)

print(mydb)

my_cursor = mydb.cursor()
query = """
    CREATE TABLE users (
        name VARCHAR(255)
        , email VARCHAR(255)
        , age INTEGER(10)
        , user_id INTEGER AUTO_INCREMENT PRIMARY KEY
    );
"""
my_cursor.execute(query)
my_cursor.execute("SHOW TABLES;")
for table in my_cursor:
    print(table[0])
  • 파일을 실행한다.
$ python database.py 
<mysql.connector.connection_cext.CMySQLConnection object at 0x0000028942314F90>
users
  • MySQL Workbench에 생성된 테이블이 만들어지는지 확인한다.

Untitled

Connect To Database in Python

개요

  • Python과 MySQL을 연동하도록 한다.
  • 프로젝트 폴더에 가상환경이 설치가 되어 있는 것으로 가정한다.
  • MySQL은 기 설치가 되어 있는 것으로 가정한다.

라이브러리 설치

  • Python과 MySQL을 연동해주는 라이브러리 종류는 다양하게 있다.
$ pip install mysql-connector mysql-connector-python

파일 작성

  • 간단하게 파일을 작성한다.
import mysql.connector

mydb = mysql.connector.connect(
    host = "localhost", 
    user = "root", 
    passwd = "evan"
)

print(mydb)
  • 파일을 실행한다.
$ python database.py 
<mysql.connector.connection_cext.CMySQLConnection object at 0x000002BF4E606090>
(venv) 

Python 코드 활용하여 DB 생성

  • 이번에는 코드를 활용하여 Schema를 생성한다.
import mysql.connector

mydb = mysql.connector.connect(
    host = "localhost", 
    user = "root", 
    passwd = "evan"
)

print(mydb)

my_cursor = mydb.cursor()
query = """
    CREATE DATABASE mulcampdb
"""

my_cursor.execute(query)

print("완료")
  • 파일을 실행한다.
$ python database.py 
<mysql.connector.connection_cext.CMySQLConnection object at 0x0000020BB6504F50>
완료
  • MySQL Workbench에서 DB가 생성되었는지 확인한다.

Untitled