blob: aa2ea7e0f3f222863a1988b9e6279d759fabdd0c [file] [log] [blame]
Don Newtone973d342018-10-26 16:44:12 -04001/*
2 Copyright 2017 the original author or authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15*/
16package impl
17
18import (
19 "fmt"
20 "log"
21 "os"
22
23 "gerrit.opencord.org/abstract-olt/internal/pkg/settings"
24 "gerrit.opencord.org/abstract-olt/models"
25 "github.com/mongodb/mongo-go-driver/bson"
26 "github.com/mongodb/mongo-go-driver/mongo"
27 "github.com/mongodb/mongo-go-driver/mongo/updateopt"
28 context "golang.org/x/net/context"
29)
30
31/*
32DoOutput - creates a backup and stores it to disk/mongodb
33*/
34func DoOutput() (bool, error) {
35 if isDirty {
36 myChan := getSyncChannel()
37 <-myChan
38 defer done(myChan, true)
39 chassisMap := models.GetChassisMap()
40 if settings.GetMongo() {
41 client, err := mongo.NewClient(settings.GetMongodb())
42 client.Connect(context.Background())
43 if err != nil {
44 log.Printf("client connect to mongo db @%s failed with %v\n", settings.GetMongodb(), err)
45 }
46 defer client.Disconnect(context.Background())
47 for clli, chassisHolder := range *chassisMap {
48 json, _ := (chassisHolder).Serialize()
49 collection := client.Database("AbstractOLT").Collection("backup")
50 doc := bson.NewDocument(bson.EC.String("_id", clli))
51 filter := bson.NewDocument(bson.EC.String("_id", clli))
52 doc.Append(bson.EC.Binary("body", json))
53
54 updateDoc := bson.NewDocument(bson.EC.SubDocument("$set", doc))
55 //update or insert if not existent
56 res, err := collection.UpdateOne(context.Background(), filter, updateDoc, updateopt.Upsert(true))
57 if err != nil {
58 log.Printf("collection.UpdateOne failed with %v\n", err)
59 } else {
60 id := res.UpsertedID
61 if settings.GetDebug() {
62 log.Printf("Update Succeeded with id %v\n", id)
63 }
64 }
65 }
66 } else {
67 for clli, chassisHolder := range *chassisMap {
68
69 json, _ := (chassisHolder).Serialize()
70 if settings.GetMongo() {
71
72 } else {
73 //TODO parameterize dump location
74 backupFile := fmt.Sprintf("backup/%s", clli)
75 f, _ := os.Create(backupFile)
76
77 defer f.Close()
78
79 _, _ = f.WriteString(string(json))
80 f.Sync()
81 }
82 }
83 }
84 isDirty = false
85 } else {
86 if settings.GetDebug() {
87 log.Print("Not dirty not dumping config")
88 }
89
90 }
91 return true, nil
92
93}