|
| 1 | +package backup |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "sync" |
| 7 | + "text/template" |
| 8 | + |
| 9 | + "github.com/aws/aws-sdk-go/aws" |
| 10 | + "github.com/aws/aws-sdk-go/service/ec2" |
| 11 | + "github.com/c2fo/lambda-ebs-backup/pkg/config" |
| 12 | + "github.com/c2fo/lambda-ebs-backup/pkg/utils" |
| 13 | +) |
| 14 | + |
| 15 | +// ManagerOpts are options to configure the backup manager |
| 16 | +type ManagerOpts struct { |
| 17 | + Client *ec2.EC2 |
| 18 | + |
| 19 | + BackupTagKey string |
| 20 | + BackupTagValue string |
| 21 | + ImageTagKey string |
| 22 | + ImageTagValue string |
| 23 | + ImageNameTag string |
| 24 | + |
| 25 | + DefaultImageNameTemplate *template.Template |
| 26 | + DefaultMaxKeepImages int |
| 27 | + |
| 28 | + Verbose bool |
| 29 | +} |
| 30 | + |
| 31 | +// NewManagerOptsFromConfig creates and initializes a new set of options from |
| 32 | +// the config. |
| 33 | +func NewManagerOptsFromConfig(client *ec2.EC2) (*ManagerOpts, error) { |
| 34 | + var err error |
| 35 | + opts := &ManagerOpts{ |
| 36 | + Client: client, |
| 37 | + BackupTagKey: config.BackupTagKey(), |
| 38 | + BackupTagValue: config.BackupTagValue(), |
| 39 | + ImageTagKey: config.ImageTagKey(), |
| 40 | + ImageTagValue: config.ImageTagValue(), |
| 41 | + ImageNameTag: config.ImageNameTag(), |
| 42 | + Verbose: true, |
| 43 | + } |
| 44 | + |
| 45 | + opts.DefaultImageNameTemplate, err = template.New("default-image-name").Parse(config.DefaultImageNameFormat()) |
| 46 | + if err != nil { |
| 47 | + return opts, err |
| 48 | + } |
| 49 | + |
| 50 | + opts.DefaultMaxKeepImages, err = config.DefaultMaxKeepImages() |
| 51 | + return opts, err |
| 52 | +} |
| 53 | + |
| 54 | +// Manager manages backups/images of ec2 resources(volumes, instances, etc.) |
| 55 | +type Manager struct { |
| 56 | + client *ec2.EC2 |
| 57 | + |
| 58 | + volumes []*ec2.Volume |
| 59 | + instances []*ec2.Instance |
| 60 | + |
| 61 | + BackupTagKey string |
| 62 | + BackupTagValue string |
| 63 | + ImageTagKey string |
| 64 | + ImageTagValue string |
| 65 | + ImageNameTag string |
| 66 | + MaxKeepImagesTag string |
| 67 | + |
| 68 | + DefaultImageNameTemplate *template.Template |
| 69 | + DefaultMaxKeepImages int |
| 70 | + |
| 71 | + Verbose bool |
| 72 | +} |
| 73 | + |
| 74 | +// NewManager creates a new backup manager from the provided options |
| 75 | +func NewManager(opts *ManagerOpts) (*Manager, error) { |
| 76 | + m := &Manager{ |
| 77 | + volumes: make([]*ec2.Volume, 0), |
| 78 | + instances: make([]*ec2.Instance, 0), |
| 79 | + } |
| 80 | + m.client = opts.Client |
| 81 | + m.BackupTagKey = opts.BackupTagKey |
| 82 | + m.BackupTagValue = opts.BackupTagValue |
| 83 | + m.ImageTagKey = opts.ImageTagKey |
| 84 | + m.ImageTagValue = opts.ImageTagValue |
| 85 | + m.ImageNameTag = opts.ImageNameTag |
| 86 | + m.Verbose = opts.Verbose |
| 87 | + if opts.DefaultImageNameTemplate == nil { |
| 88 | + return nil, fmt.Errorf("DefaultImageNameTemplate is a required field for ManagerOpts") |
| 89 | + } |
| 90 | + |
| 91 | + m.DefaultImageNameTemplate = opts.DefaultImageNameTemplate |
| 92 | + m.DefaultMaxKeepImages = opts.DefaultMaxKeepImages |
| 93 | + return m, nil |
| 94 | +} |
| 95 | + |
| 96 | +// Search searches for a volumes and instances to backup |
| 97 | +func (m *Manager) Search() error { |
| 98 | + return m.all( |
| 99 | + []func() error{ |
| 100 | + m.searchVolumes, |
| 101 | + m.searchInstances, |
| 102 | + }, |
| 103 | + ) |
| 104 | +} |
| 105 | + |
| 106 | +func (m *Manager) searchVolumes() error { |
| 107 | + params := &ec2.DescribeVolumesInput{ |
| 108 | + Filters: []*ec2.Filter{ |
| 109 | + &ec2.Filter{ |
| 110 | + Name: aws.String(fmt.Sprintf("tag:%s", m.BackupTagKey)), |
| 111 | + Values: []*string{aws.String(m.BackupTagValue)}, |
| 112 | + }, |
| 113 | + }, |
| 114 | + MaxResults: aws.Int64(500), |
| 115 | + } |
| 116 | + |
| 117 | + m.logf("Searching for volumes with tag %s:%s\n", m.BackupTagKey, m.BackupTagValue) |
| 118 | + |
| 119 | + return m.client.DescribeVolumesPages(params, |
| 120 | + func(page *ec2.DescribeVolumesOutput, lastPage bool) bool { |
| 121 | + for _, v := range page.Volumes { |
| 122 | + m.volumes = append(m.volumes, v) |
| 123 | + } |
| 124 | + return !lastPage |
| 125 | + }) |
| 126 | +} |
| 127 | + |
| 128 | +func (m *Manager) searchInstances() error { |
| 129 | + params := &ec2.DescribeInstancesInput{ |
| 130 | + Filters: []*ec2.Filter{ |
| 131 | + &ec2.Filter{ |
| 132 | + Name: aws.String(fmt.Sprintf("tag:%s", m.ImageTagKey)), |
| 133 | + Values: []*string{aws.String(m.ImageTagValue)}, |
| 134 | + }, |
| 135 | + }, |
| 136 | + MaxResults: aws.Int64(500), |
| 137 | + } |
| 138 | + |
| 139 | + m.logf("Searching for instances with tag %s:%s\n", m.ImageTagKey, m.ImageTagValue) |
| 140 | + |
| 141 | + return m.client.DescribeInstancesPages(params, |
| 142 | + func(page *ec2.DescribeInstancesOutput, lastPage bool) bool { |
| 143 | + for _, r := range page.Reservations { |
| 144 | + for _, i := range r.Instances { |
| 145 | + tags := utils.TagSliceToMap(i.Tags) |
| 146 | + m.logf( |
| 147 | + "Found instance %s(%s) with matching tag\n", |
| 148 | + aws.StringValue(i.InstanceId), |
| 149 | + tags.GetDefault("Name", "<no value>"), |
| 150 | + ) |
| 151 | + m.instances = append(m.instances, i) |
| 152 | + } |
| 153 | + } |
| 154 | + return !lastPage |
| 155 | + }) |
| 156 | +} |
| 157 | + |
| 158 | +// Backup performs the necessary backups |
| 159 | +func (m *Manager) Backup() error { |
| 160 | + return m.all( |
| 161 | + []func() error{ |
| 162 | + m.backupVolumes, |
| 163 | + m.backupInstances, |
| 164 | + }, |
| 165 | + ) |
| 166 | +} |
| 167 | + |
| 168 | +func (m *Manager) backupVolumes() error { |
| 169 | + var wg sync.WaitGroup |
| 170 | + errorChan := make(chan error, 1) |
| 171 | + |
| 172 | + for _, volume := range m.volumes { |
| 173 | + wg.Add(1) |
| 174 | + go func(v *ec2.Volume) { |
| 175 | + defer wg.Done() |
| 176 | + snap, err := m.client.CreateSnapshot(&ec2.CreateSnapshotInput{ |
| 177 | + VolumeId: v.VolumeId, |
| 178 | + }) |
| 179 | + if err != nil { |
| 180 | + m.logf("Error creating snapshot for volume '%s'\n", aws.StringValue(v.VolumeId)) |
| 181 | + errorChan <- err |
| 182 | + } else { |
| 183 | + m.logf("Created snapshot '%s' for volume '%s'\n", |
| 184 | + aws.StringValue(snap.SnapshotId), |
| 185 | + aws.StringValue(v.VolumeId), |
| 186 | + ) |
| 187 | + } |
| 188 | + }(volume) |
| 189 | + } |
| 190 | + |
| 191 | + wg.Wait() |
| 192 | + |
| 193 | + select { |
| 194 | + case err := <-errorChan: |
| 195 | + return err |
| 196 | + default: |
| 197 | + } |
| 198 | + |
| 199 | + return nil |
| 200 | +} |
| 201 | + |
| 202 | +func (m *Manager) backupInstances() error { |
| 203 | + var wg sync.WaitGroup |
| 204 | + errorChan := make(chan error, 1) |
| 205 | + |
| 206 | + for _, instance := range m.instances { |
| 207 | + wg.Add(1) |
| 208 | + go func(i *ec2.Instance) { |
| 209 | + defer wg.Done() |
| 210 | + tags := utils.TagSliceToMap(i.Tags) |
| 211 | + imageName, err := m.formatImageName(i) |
| 212 | + if err != nil { |
| 213 | + errorChan <- err |
| 214 | + return |
| 215 | + } |
| 216 | + |
| 217 | + image, err := m.client.CreateImage(&ec2.CreateImageInput{ |
| 218 | + InstanceId: i.InstanceId, |
| 219 | + Name: aws.String(imageName), |
| 220 | + }) |
| 221 | + if err != nil { |
| 222 | + m.logf( |
| 223 | + "Error creating image for instance %s(%s): %s\n", |
| 224 | + aws.StringValue(i.InstanceId), |
| 225 | + tags.GetDefault("Name", ""), |
| 226 | + err, |
| 227 | + ) |
| 228 | + errorChan <- err |
| 229 | + return |
| 230 | + } |
| 231 | + |
| 232 | + m.logf("Created image '%s'(%s) for instance '%s'(%s)\n", |
| 233 | + aws.StringValue(image.ImageId), |
| 234 | + imageName, |
| 235 | + aws.StringValue(i.InstanceId), |
| 236 | + tags.GetDefault("Name", ""), |
| 237 | + ) |
| 238 | + }(instance) |
| 239 | + } |
| 240 | + |
| 241 | + wg.Wait() |
| 242 | + |
| 243 | + select { |
| 244 | + case err := <-errorChan: |
| 245 | + return err |
| 246 | + default: |
| 247 | + } |
| 248 | + |
| 249 | + return nil |
| 250 | +} |
| 251 | + |
| 252 | +func (m *Manager) all(funcs []func() error) error { |
| 253 | + var wg sync.WaitGroup |
| 254 | + errorChan := make(chan error, 1) |
| 255 | + |
| 256 | + for _, function := range funcs { |
| 257 | + wg.Add(1) |
| 258 | + go func(f func() error) { |
| 259 | + defer wg.Done() |
| 260 | + if err := f(); err != nil { |
| 261 | + errorChan <- err |
| 262 | + } |
| 263 | + }(function) |
| 264 | + } |
| 265 | + |
| 266 | + wg.Wait() |
| 267 | + |
| 268 | + select { |
| 269 | + case err := <-errorChan: |
| 270 | + return err |
| 271 | + default: |
| 272 | + } |
| 273 | + |
| 274 | + return nil |
| 275 | +} |
| 276 | + |
| 277 | +func (m *Manager) formatImageName(i *ec2.Instance) (string, error) { |
| 278 | + var nameTemplate *template.Template |
| 279 | + var err error |
| 280 | + tags := utils.TagSliceToMap(i.Tags) |
| 281 | + instanceIDString := aws.StringValue(i.InstanceId) |
| 282 | + |
| 283 | + // User has supplied a template overide for naming the image. We'll need to |
| 284 | + // template it out. |
| 285 | + if templateString, ok := tags.Get(m.ImageNameTag); ok { |
| 286 | + templateName := fmt.Sprintf("image-name-%s", instanceIDString) |
| 287 | + m.logf("Using custom image name template for instance '%s'\n", instanceIDString) |
| 288 | + nameTemplate, err = template.New(templateName).Parse(templateString) |
| 289 | + if err != nil { |
| 290 | + return "", err |
| 291 | + } |
| 292 | + } else { |
| 293 | + m.logf("Using DefaultImageNameTemplate for instance '%s'\n", instanceIDString) |
| 294 | + nameTemplate = m.DefaultImageNameTemplate |
| 295 | + } |
| 296 | + |
| 297 | + var buf bytes.Buffer |
| 298 | + // Execute the template |
| 299 | + err = nameTemplate.Execute(&buf, newImageNameTemplateContext(i)) |
| 300 | + return buf.String(), err |
| 301 | +} |
| 302 | + |
| 303 | +func (m *Manager) log(v ...interface{}) { |
| 304 | + if m.Verbose { |
| 305 | + fmt.Println(v...) |
| 306 | + } |
| 307 | +} |
| 308 | + |
| 309 | +func (m *Manager) logf(format string, v ...interface{}) { |
| 310 | + if m.Verbose { |
| 311 | + fmt.Printf(format, v...) |
| 312 | + } |
| 313 | +} |
0 commit comments