Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite5015e4

Browse files
committed
Merge pull requestsorintlab#133 from robdaemon/set_superuser_password
Setting the initial pgsql superuser password
2 parentsad40a86 +16dcdb1 commite5015e4

File tree

8 files changed

+133
-70
lines changed

8 files changed

+133
-70
lines changed

‎cmd/keeper/keeper.go

Lines changed: 49 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -57,20 +57,22 @@ var cmdKeeper = &cobra.Command{
5757
}
5858

5959
typeconfigstruct {
60-
idstring
61-
storeBackendstring
62-
storeEndpointsstring
63-
dataDirstring
64-
clusterNamestring
65-
listenAddressstring
66-
portstring
67-
pgListenAddressstring
68-
pgPortstring
69-
pgBinPathstring
70-
pgConfDirstring
71-
pgSUUsernamestring
72-
pgSUPasswordstring
73-
debugbool
60+
idstring
61+
storeBackendstring
62+
storeEndpointsstring
63+
dataDirstring
64+
clusterNamestring
65+
listenAddressstring
66+
portstring
67+
pgListenAddressstring
68+
pgPortstring
69+
pgBinPathstring
70+
pgConfDirstring
71+
pgSUUsernamestring
72+
pgSUPasswordstring
73+
debugbool
74+
pgInitialSUUsernamestring
75+
pgInitialSUPasswordFilestring
7476
}
7577

7678
varcfgconfig
@@ -93,6 +95,8 @@ func init() {
9395
cmdKeeper.PersistentFlags().StringVar(&cfg.pgConfDir,"pg-conf-dir","","absolute path to user provided postgres configuration. If empty a default dir under $dataDir/postgres/conf.d will be used")
9496
cmdKeeper.PersistentFlags().StringVar(&cfg.pgSUUsername,"pg-su-username","","postgres superuser user name (required by pg_rewind)")
9597
cmdKeeper.PersistentFlags().StringVar(&cfg.pgSUPassword,"pg-su-password","","postgres superuser password (required by pg_rewind)")
98+
cmdKeeper.PersistentFlags().StringVar(&cfg.pgInitialSUUsername,"initial-pg-su-username","","postgres initial superuser username")
99+
cmdKeeper.PersistentFlags().StringVar(&cfg.pgInitialSUPasswordFile,"initial-pg-su-password-file","","postgres initial superuser password secret file")
96100
cmdKeeper.PersistentFlags().BoolVar(&cfg.debug,"debug",false,"enable debug logging")
97101
}
98102

@@ -103,7 +107,33 @@ var defaultPGParameters = pg.Parameters{
103107
"hot_standby":"on",
104108
}
105109

106-
func (p*PostgresKeeper)getSUConnParams(keeperState*cluster.KeeperState,setPasswordbool) pg.ConnParams {
110+
func (p*PostgresKeeper)getPgInitialSUPassword()string {
111+
varpwstring
112+
113+
ifp.cfg.pgInitialSUPasswordFile!="" {
114+
fi,err:=os.Lstat(p.cfg.pgInitialSUPasswordFile)
115+
iferr!=nil {
116+
log.Errorf("Unable to read password from file %s, error: %v",p.cfg.pgInitialSUPasswordFile,err)
117+
returnpw
118+
}
119+
120+
iffi.Mode()>0600 {
121+
//TODO: enforce this by exiting with an error. Kubernetes makes this file too open today.
122+
log.Warningf("Password file %s permissions %#o are too open. This file should only be readable to the user executing stolon! Continuing...",p.cfg.pgInitialSUPasswordFile,fi.Mode())
123+
}
124+
125+
pwBytes,err:=ioutil.ReadFile(p.cfg.pgInitialSUPasswordFile)
126+
iferr!=nil {
127+
log.Errorf("Unable to read password from file %s, error: %v",p.cfg.pgInitialSUPasswordFile,err)
128+
returnpw
129+
}
130+
pw=strings.TrimSpace(string(pwBytes))
131+
}
132+
133+
returnpw
134+
}
135+
136+
func (p*PostgresKeeper)getSUConnParams(keeperState*cluster.KeeperState) pg.ConnParams {
107137
cp:= pg.ConnParams{
108138
"user":p.cfg.pgSUUsername,
109139
"password":p.cfg.pgSUPassword,
@@ -113,9 +143,6 @@ func (p *PostgresKeeper) getSUConnParams(keeperState *cluster.KeeperState, setPa
113143
"dbname":"postgres",
114144
"sslmode":"disable",
115145
}
116-
ifsetPassword {
117-
cp["password"]=p.cfg.pgSUPassword
118-
}
119146
returncp
120147
}
121148

@@ -382,7 +409,9 @@ func (p *PostgresKeeper) Start() {
382409
// and RequestTimeout) after a changed cluster config
383410
followersIDs:=cv.GetFollowersIDs(p.id)
384411
pgParameters:=p.createPGParameters(followersIDs)
385-
pgm:=postgresql.NewManager(p.id,p.cfg.pgBinPath,p.cfg.dataDir,p.cfg.pgConfDir,pgParameters,p.getOurConnParams().ConnString(),p.getOurReplConnParams().ConnString(),p.clusterConfig.PGReplUser,p.clusterConfig.PGReplPassword,p.clusterConfig.RequestTimeout)
412+
pgm:=postgresql.NewManager(p.id,p.cfg.pgBinPath,p.cfg.dataDir,p.cfg.pgConfDir,pgParameters,p.getOurConnParams().ConnString(),
413+
p.getOurReplConnParams().ConnString(),p.clusterConfig.PGReplUser,p.clusterConfig.PGReplPassword,
414+
p.cfg.pgInitialSUUsername,p.getPgInitialSUPassword(),p.clusterConfig.RequestTimeout)
386415
p.pgm=pgm
387416

388417
p.pgm.Stop(true)
@@ -457,7 +486,7 @@ func (p *PostgresKeeper) Resync(followed *cluster.KeeperState, initialized, star
457486
// doesn't exists pgm.SyncFromFollowedPGRewind will return an error and
458487
// fallback to pg_basebackup
459488
ifinitialized&&p.clusterConfig.UsePGRewind&&p.cfg.hasPGRewindRequiredOptions() {
460-
connParams:=p.getSUConnParams(followed,false)
489+
connParams:=p.getSUConnParams(followed)
461490
log.Infof("syncing using pg_rewind from followed instance %q",followed.ID)
462491
iferr:=pgm.SyncFromFollowedPGRewind(connParams,p.cfg.pgSUPassword);err!=nil {
463492
// log pg_rewind error and fallback to pg_basebackup

‎cmd/sentinel/sentinel.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ type config struct {
5959
keeperPortstring
6060
keeperKubeLabelSelectorstring
6161
initialClusterConfigstring
62+
kubernetesNamespacestring
6263
debugbool
6364
}
6465

@@ -73,6 +74,7 @@ func init() {
7374
cmdSentinel.PersistentFlags().StringVar(&cfg.keeperKubeLabelSelector,"keeper-kube-label-selector","","label selector for discoverying stolon-keeper(s) under kubernetes")
7475
cmdSentinel.PersistentFlags().StringVar(&cfg.keeperPort,"keeper-port","5431","stolon-keeper(s) listening port (used by kubernetes discovery)")
7576
cmdSentinel.PersistentFlags().StringVar(&cfg.initialClusterConfig,"initial-cluster-config","","a file providing the initial cluster config, used only at cluster initialization, ignored if cluster is already initialized")
77+
cmdSentinel.PersistentFlags().StringVar(&cfg.kubernetesNamespace,"kubernetes-namespace","default","the Kubernetes namespace stolon is deployed under")
7678
cmdSentinel.PersistentFlags().BoolVar(&cfg.debug,"debug",false,"enable debug logging")
7779
}
7880

@@ -272,7 +274,7 @@ func (s *Sentinel) getKubernetesPodsIPs(ctx context.Context) ([]string, error) {
272274
}
273275
host:=os.Getenv("KUBERNETES_SERVICE_HOST")
274276
port:=os.Getenv("KUBERNETES_SERVICE_PORT")
275-
u,err:=url.Parse(fmt.Sprintf("https://%s:%s/api/v1/namespaces/default/pods",host,port))
277+
u,err:=url.Parse(fmt.Sprintf("https://%s:%s/api/v1/namespaces/%s/pods",host,port,cfg.kubernetesNamespace))
276278
iferr!=nil {
277279
returnnil,err
278280
}

‎examples/kubernetes/README.md

Lines changed: 10 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@ kubectl create -f stolon-sentinel.yaml
2727

2828
This will create a replication controller with one pod executing the stolon sentinel. You can also increase the number of replicas for stolon sentinels in the rc definition or do it later.
2929

30+
###Create the keeper's password secret
31+
32+
This creates a password secret that can be used by the keeper to set up the initial database user. This example uses the value 'password1' but you will want to replace the value with a Base64-encoded password of your choice.
33+
34+
```
35+
kubectl create -f secret.yaml
36+
```
37+
3038
###Create the first stolon keeper
3139
Note: In this example the stolon keeper is a replication controller that, for every pod replica, uses a volume for stolon and postgreSQL data of`emptyDir` type. So it'll go away when the related pod is destroyed. This is just for easy testing. In production you should use a persistent volume. Actually (kubernetes 1.0), for working with persistent volumes you should define a different replication controller with`replicas=1` for every keeper instance.
3240

@@ -52,34 +60,6 @@ NAME READY STATUS RESTARTS AGE
5260
stolon-keeper-rc-qpqp9 1/1 Running 0 1m
5361
```
5462

55-
####Enter the pod
56-
57-
```
58-
kubectl exec stolon-keeper-rc-qpqp9 -it /bin/bash
59-
60-
[root@stolon-keeper-rc-hwqxd /]#
61-
```
62-
63-
now become the`stolon` user:
64-
```
65-
[root@stolon-keeper-rc-hwqxd /]# su - stolon
66-
67-
[stolon@stolon-keeper-rc-hwqxd ~]$
68-
```
69-
70-
connect to the postgres instance and create a password for the`stolon` superuser:
71-
72-
```
73-
[stolon@stolon-keeper-rc-hwqxd ~]$ psql -h localhost -p 5432 postgres
74-
psql (9.4.4)
75-
Type "help" for help.
76-
77-
postgres=# alter role stolon with password 'stolon';
78-
ALTER ROLE
79-
```
80-
you can now exit the shell.
81-
82-
8363
###Create the proxies
8464

8565
```
@@ -107,6 +87,8 @@ stolon-proxy-service <none> stolon-cluster=
10787

10888
####Connect to the proxy service
10989

90+
The password for the stolon user will be the value specified in your`secret.yaml` above (or`password1` if you did not change it).
91+
11092
```
11193
psql --host 10.247.50.217 --port 5432 postgres -U stolon -W
11294
Password for user stolon:

‎examples/kubernetes/secret.yaml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
apiVersion:v1
3+
kind:Secret
4+
metadata:
5+
name:stolon
6+
type:Opaque
7+
data:
8+
password:cGFzc3dvcmQxCg==

‎examples/kubernetes/stolon-keeper.yaml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,21 @@ spec:
2929
# Enable debugging
3030
-name:STKEEPER_DEBUG
3131
value:"true"
32+
-name:STKEEPER_INITIAL_PG_SU_USERNAME
33+
value:"stolon"
34+
-name:STKEEPER_INITIAL_PG_SU_PASSWORD_FILE
35+
value:"/etc/secrets/stolon/password"
3236
ports:
3337
-containerPort:5431
3438
-containerPort:5432
3539
volumeMounts:
3640
-mountPath:/stolon-data
3741
name:data
42+
-mountPath:/etc/secrets/stolon
43+
name:stolon
3844
volumes:
3945
-name:data
4046
emptyDir:{}
47+
-name:stolon
48+
secret:
49+
secretName:stolon

‎examples/kubernetes/stolon-sentinel.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,7 @@ spec:
3030
# Enable debugging
3131
-name:STSENTINEL_DEBUG
3232
value:"true"
33+
-name:STSENTINEL_KUBERNETES_NAMESPACE
34+
value:"default"
3335
ports:
3436
-containerPort:6431

‎pkg/postgresql/postgresql.go

Lines changed: 41 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,18 @@ var (
4040
)
4141

4242
typeManagerstruct {
43-
namestring
44-
dataDirstring
45-
replUserstring
46-
replPasswordstring
47-
localConnStringstring
48-
replConnStringstring
49-
pgBinPathstring
50-
requestTimeout time.Duration
51-
parametersParameters
52-
confDirstring
43+
namestring
44+
dataDirstring
45+
replUserstring
46+
replPasswordstring
47+
localConnStringstring
48+
replConnStringstring
49+
pgBinPathstring
50+
requestTimeout time.Duration
51+
parametersParameters
52+
confDirstring
53+
initialSUUsernamestring
54+
initialSUPasswordstring
5355
}
5456

5557
typeParametersmap[string]string
@@ -75,18 +77,20 @@ func (s Parameters) Equals(is Parameters) bool {
7577
returnreflect.DeepEqual(s,is)
7678
}
7779

78-
funcNewManager(namestring,pgBinPathstring,dataDirstring,confDirstring,parametersParameters,localConnString,replConnString,replUser,replPasswordstring,requestTimeout time.Duration)*Manager {
80+
funcNewManager(namestring,pgBinPathstring,dataDirstring,confDirstring,parametersParameters,localConnString,replConnString,replUser,replPassword,initialSUUsername,initialSUPasswordstring,requestTimeout time.Duration)*Manager {
7981
return&Manager{
80-
name:name,
81-
dataDir:filepath.Join(dataDir,"postgres"),
82-
replUser:replUser,
83-
replPassword:replPassword,
84-
localConnString:localConnString,
85-
replConnString:replConnString,
86-
pgBinPath:pgBinPath,
87-
requestTimeout:requestTimeout,
88-
parameters:parameters,
89-
confDir:confDir,
82+
name:name,
83+
dataDir:filepath.Join(dataDir,"postgres"),
84+
replUser:replUser,
85+
replPassword:replPassword,
86+
localConnString:localConnString,
87+
replConnString:replConnString,
88+
pgBinPath:pgBinPath,
89+
requestTimeout:requestTimeout,
90+
parameters:parameters,
91+
confDir:confDir,
92+
initialSUUsername:initialSUUsername,
93+
initialSUPassword:initialSUPassword,
9094
}
9195
}
9296

@@ -130,6 +134,15 @@ func (p *Manager) Init() error {
130134
err=fmt.Errorf("error starting instance: %v",err)
131135
goto out
132136
}
137+
138+
ifp.initialSUPassword!=""&&p.initialSUUsername!="" {
139+
log.Infof("Setting initial PostgreSQL password")
140+
iferr=p.SetInitialPassword();err!=nil {
141+
err=fmt.Errorf("error setting initial password for '%s' user: %v",p.initialSUUsername,err)
142+
goto out
143+
}
144+
}
145+
133146
log.Infof("Creating replication role")
134147
iferr=p.CreateReplRole();err!=nil {
135148
err=fmt.Errorf("error creating replication role: %v",err)
@@ -139,6 +152,7 @@ func (p *Manager) Init() error {
139152
err=fmt.Errorf("error stopping instance: %v",err)
140153
goto out
141154
}
155+
142156
// On every error remove the dataDir, so we don't end with an half initialized database
143157
out:
144158
iferr!=nil {
@@ -231,6 +245,12 @@ func (p *Manager) Promote() error {
231245
returnnil
232246
}
233247

248+
func (p*Manager)SetInitialPassword()error {
249+
ctx,cancel:=context.WithTimeout(context.Background(),p.requestTimeout)
250+
defercancel()
251+
returnSetInitialPassword(ctx,p.localConnString,p.initialSUUsername,p.initialSUPassword)
252+
}
253+
234254
func (p*Manager)CreateReplRole()error {
235255
ctx,cancel:=context.WithTimeout(context.Background(),p.requestTimeout)
236256
defercancel()

‎pkg/postgresql/utils.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,17 @@ func CheckDBStatus(ctx context.Context, connString string) error {
8989
returnnil
9090
}
9191

92+
funcSetInitialPassword(ctx context.Context,connString,superuser,initialPasswordstring)error {
93+
db,err:=sql.Open("postgres",connString)
94+
iferr!=nil {
95+
returnerr
96+
}
97+
deferdb.Close()
98+
99+
_,err=Exec(ctx,db,fmt.Sprintf(`alter user %s with password '%s';`,superuser,initialPassword))
100+
returnerr
101+
}
102+
92103
funcCreateReplRole(ctx context.Context,connString,replUser,replPasswordstring)error {
93104
db,err:=sql.Open("postgres",connString)
94105
iferr!=nil {

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp