/
consul.go
185 lines (163 loc) · 5.57 KB
/
consul.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// Copyright 2018 Bull S.A.S. Atos Technologies - Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois, France.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"io"
"os"
"strconv"
"github.com/ystia/yorc/v4/config"
"github.com/blang/semver"
"github.com/hashicorp/consul/api"
"github.com/pkg/errors"
"github.com/ystia/yorc/v4/helper/consulutil"
"github.com/ystia/yorc/v4/log"
"github.com/ystia/yorc/v4/server/upgradeschema"
)
var upgradeToMap = map[string]func(config.Configuration, *api.KV, <-chan struct{}) error{
"1.0.0": upgradeschema.UpgradeFromPre31,
"1.1.0": upgradeschema.UpgradeTo110,
"1.1.1": upgradeschema.UpgradeTo111,
"1.1.2": upgradeschema.UpgradeTo112,
"1.2.0": upgradeschema.UpgradeTo120,
"1.3.0": upgradeschema.UpgradeTo130,
"1.3.1": upgradeschema.UpgradeTo131,
}
var orderedUpgradesVersions []semver.Version
var disableConsulSnapshotsOnUpgrades bool
func init() {
for v := range upgradeToMap {
orderedUpgradesVersions = append(orderedUpgradesVersions, semver.MustParse(v))
}
semver.Sort(orderedUpgradesVersions)
var err error
disableConsulSnapEnv := os.Getenv("YORC_DISABLE_CONSUL_SNAPSHOTS_ON_UPGRADE")
if disableConsulSnapEnv != "" {
disableConsulSnapshotsOnUpgrades, err = strconv.ParseBool(disableConsulSnapEnv)
if err != nil {
log.Panicf(`Can't read value of "YORC_DISABLE_CONSUL_SNAPSHOTS_ON_UPGRADE" environment variable: %v`, err)
}
}
}
func synchronizeDBUpdate(client *api.Client) (*api.Lock, <-chan struct{}, error) {
lock, err := client.LockOpts(&api.LockOptions{
Key: consulutil.YorcSchemaVersionPath + ".lock",
// Value: []byte("check"),
LockTryOnce: true,
// LockWaitTime: 10 * time.Millisecond,
})
if err != nil {
return nil, nil, errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
var leaderCh <-chan struct{}
for leaderCh == nil {
log.Debug("Try to acquire lock for DB schema update check")
leaderCh, err = lock.Lock(nil)
if err != nil {
return nil, nil, errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
}
log.Debug("Lock for DB schema update check acquired")
return lock, leaderCh, nil
}
func setupConsulDBSchema(cfg config.Configuration, client *api.Client) error {
lock, leaderCh, err := synchronizeDBUpdate(client)
if err != nil {
return err
}
defer func() {
lock.Unlock()
// will fail if another instance take it but will cleanup if it is the last one
lock.Destroy()
}()
kv := client.KV()
kvp, _, err := kv.Get(consulutil.YorcSchemaVersionPath, nil)
if err != nil {
return errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
// If there is no version it could mean either that:
// 1/ we are updating from a pre-3.1 release
// 2/ we are the first server to boot for the first time
if kvp == nil {
kvps, _, err := kv.Keys(consulutil.DeploymentKVPrefix+"/", "/", nil)
if err != nil {
return errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
if len(kvps) > 0 {
return upgradeFromVersion(cfg, client, leaderCh, "0.0.0")
}
return setNewVersion()
}
return upgradeFromVersion(cfg, client, leaderCh, string(kvp.Value))
}
func setNewVersion() error {
err := consulutil.StoreConsulKeyAsString(consulutil.YorcSchemaVersionPath, consulutil.YorcSchemaVersion)
if err != nil {
return err
}
return nil
}
func upgradeFromVersion(cfg config.Configuration, client *api.Client, leaderCh <-chan struct{}, fromVersion string) error {
vCurrent, err := semver.Make(fromVersion)
if err != nil {
return errors.Wrapf(err, "failed to parse current version of consul db schema")
}
vNew, err := semver.Make(consulutil.YorcSchemaVersion)
if err != nil {
return errors.Wrapf(err, "failed to parse current version of consul db schema")
}
switch vNew.Compare(vCurrent) {
case 0:
// Same version nothing to do
return nil
case 1:
err = performUpgrade(cfg, client, leaderCh, vCurrent)
if err != nil {
return err
}
case -1:
return errors.Errorf("this version of Yorc is too old compared to the current DB schema (%s), an upgrade is needed.", vCurrent)
}
return setNewVersion()
}
func performUpgrade(cfg config.Configuration, client *api.Client, leaderCh <-chan struct{}, vCurrent semver.Version) error {
snap := client.Snapshot()
var snapReader io.ReadCloser
if !disableConsulSnapshotsOnUpgrades {
// Make a Consul snapshot and restore it if any error occurs
var err error
snapReader, _, err = snap.Save(nil)
if err != nil {
return errors.Wrapf(err, "failed to upgrade consul db schema to %q", err)
}
defer snapReader.Close()
}
for _, vUp := range orderedUpgradesVersions {
if vUp.GT(vCurrent) {
err := upgradeToMap[vUp.String()](cfg, client.KV(), leaderCh)
if err != nil {
if !disableConsulSnapshotsOnUpgrades {
// Restore Consul snapshot
restoreErr := snap.Restore(nil, snapReader)
if restoreErr != nil {
log.Printf("failed to restore consul db schema to %q due to error:%+v", vCurrent, restoreErr)
} else {
log.Printf("As any error occurred, schema has been successfully restored to version %q", vCurrent)
}
}
return errors.Wrapf(err, "failed to upgrade consul db schema to %q.", vUp)
}
}
}
return nil
}