package autoshundb import ( "context" "errors" "fmt" "net/url" "os" "time" "github.com/sirupsen/logrus" "github.rackspace.com/gorax/tools/passkey" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" ) const ( dbName = "infrastructure" collName = "autoshun_f5" defaultTimeout = 10 * time.Second ) var log *logrus.Entry // ErrNotFound : Standard error returned when the device is not found in the database var ErrNotFound = mongo.ErrNoDocuments // Shun definition in DB type Shun struct { DateAdded time.Time `bson:"date_added" json:"date_added"` // Date passed from PEG on when this shun will be removed, reference only RemoveDate time.Time `bson:"remove_date" json:"remove_date"` // PEG Incident ID that added this IP IncidentID string `bson:"incident_id" json:"incident_id"` // Length of the shun (time.Duration converts to an int64 expressing the duration in nano seconds) ShunLength time.Duration `json:"shun_length" bson:"shun_length"` } // LogEntry : Log entry for a device, keeps track of what changes were made to a device in the db type LogEntry struct { // Time stamp of the action Time time.Time `bson:"time" json:"time"` // Action that was performed, device created, shun added, removed, etc Action string `bson:"action" json:"action"` // User that performed the action User string `bson:"user" json:"user"` // X-Request ID of connection that performed this action RequestID string `bson:"x-connection-id" json:"x-connection-id"` } // Device definition in DB type Device struct { ID primitive.ObjectID `bson:"_id,omitempty" json:"_id,omitempty"` Device string `bson:"device" json:"device"` LastUpdated time.Time `bson:"last_updated" json:"last_updated"` Shuns map[string]Shun `bson:"shuns" json:"shuns"` Log []LogEntry `bson:"log" json:"log"` } // Client : DB Client type Client struct { db *mongo.Client coll *mongo.Collection } func pkInit(staging bool) (*passkey.Client, error) { log.Debug("Initializing passkey") pkUser := os.Getenv("PASSKEY_USER") pkPass := os.Getenv("PASSKEY_PASS") var pk *passkey.Client var err error if pkUser != "" { log.Debug("PASSKEY_USER is set, using environment variable to initialize passkey") pk, err = passkey.New(pkUser, pkPass, staging) if err != nil { return nil, err } } else { log.Debug("PASSKEY_USER not set, attempting to use file to initialize passkey") pk, err = passkey.NewFromFile("netsec01", "", staging) if err != nil { return nil, err } } return pk, nil } // New : Creates a new instance of the DB client. Log is optional and will override the packages default logging // staging will control which password safe is used and which instance of object rocket is connected to func New(staging bool, pk *passkey.Client, logger *logrus.Entry) (*Client, error) { var err error log = logger log.WithField("staging", staging).Debug("Initializing autoshundb client") // if we weren't given a passkey (i.e. for testing) then initialize it ourselves. if pk == nil { pk, err = pkInit(staging) if err != nil { return nil, err } } mongoURI := fmt.Sprintf(`mongodb://%s:%s@%s/%s?ssl=true`, pk.Keys.Mongo.NSIMongoUser.Credential.Username, url.QueryEscape(pk.Keys.Mongo.NSIMongoUser.Credential.Password), pk.Keys.Mongo.NSIMongoUser.Credential.HostName, dbName, ) log.Debugf("nsi host: %s", pk.Keys.Mongo.NSIMongoUser.Credential.HostName) c := new(Client) log.Debug("Connecting to mongo...") ctx, _ := context.WithTimeout(context.Background(), defaultTimeout) c.db, err = mongo.Connect(ctx, options.Client().ApplyURI(mongoURI)) if err != nil { log.WithError(err).Error("error connecting to mongo") return nil, err } log.Debug("Connection established, pinging") // Make sure we can contact the server if err := c.db.Ping(ctx, readpref.Primary()); err != nil { log.WithError(err).Error("error pinging mongo") return nil, err } log.Debug("Ping successful") c.coll = c.db.Database(dbName).Collection(collName) return c, nil } // NewDevice : Creates a new blank device and inserts it in to the DB func (c *Client) NewDevice(deviceID, user, reqID string) (*Device, error) { d := Device{ Device: deviceID, LastUpdated: time.Now(), Log: []LogEntry{ { Time: time.Now(), Action: "Device Created", User: user, RequestID: reqID, }, }, Shuns: make(map[string]Shun), } ctx, _ := context.WithTimeout(context.Background(), defaultTimeout) res, err := c.coll.InsertOne(ctx, d) if err != nil { log.Error(err) return nil, err } if res.InsertedID == nil { return nil, fmt.Errorf("insert one command returned no response") } d.ID = res.InsertedID.(primitive.ObjectID) return &d, nil } // Find : Performs a Find with provided filter and projection func (c *Client) Find(filter, projection bson.D) ([]Device, error) { ctx, _ := context.WithTimeout(context.Background(), 30*time.Second) cur, err := c.coll.Find(context.Background(), filter, options.Find().SetProjection(projection)) if err != nil { return nil, err } defer cur.Close(ctx) var devs []Device for cur.Next(ctx) { var d Device if err := cur.Decode(&d); err != nil { return nil, err } devs = append(devs, d) } return devs, nil } // All : Returns all devices in the DB func (c *Client) All() ([]Device, error) { var devs []Device ctx, _ := context.WithTimeout(context.Background(), 30*time.Second) cursor, err := c.coll.Find(ctx, bson.D{}) // find all entries if err != nil { return nil, err } defer cursor.Close(ctx) for cursor.Next(ctx) { var result Device err := cursor.Decode(&result) if err != nil { return nil, err } devs = append(devs, result) } if err := cursor.Err(); err != nil { return nil, err } return devs, nil } // FindDevice : Return an existing device from the DB func (c *Client) FindDevice(deviceID string) (*Device, error) { ctx, _ := context.WithTimeout(context.Background(), defaultTimeout) filter := bson.M{"device": deviceID} res := new(Device) err := c.coll.FindOne(ctx, filter).Decode(res) if err != nil { log.Error(err) return nil, err } return res, nil } // updateDevice : Update an existing device in the DB func (c *Client) updateDevice(d *Device) error { ctx, _ := context.WithTimeout(context.Background(), defaultTimeout) filter := bson.M{"_id": d.ID} update := bson.D{ {"$set", bson.D{ {"last_udpated", time.Now()}, {"shuns", d.Shuns}, {"log", d.Log}, }}, } updateResult, err := c.coll.UpdateOne(ctx, filter, update, options.Update().SetUpsert(false)) if err != nil { log.Error() return err } if updateResult.MatchedCount != 1 && updateResult.ModifiedCount != 1 { s := fmt.Sprintf("matched count and modified count do not equal 1: MatchedCount: %d, ModifiedCount: %d", updateResult.MatchedCount, updateResult.ModifiedCount) log.Error(s) return errors.New(s) } return nil } func (d *Device) logEntry(action, user, reqID string) { d.Log = append(d.Log, LogEntry{ Time: time.Now(), Action: action, User: user, RequestID: reqID, }) } // FindShun : Looks through shuns in the DB for a specific shun. Nil if not found. func (d *Device) FindShun(ip string) *Shun { for i, s := range d.Shuns { if i == ip { return &s } } return nil } // AddShun : Add a new shun to the entry func (c *Client) AddShun( d *Device, ip, user, incidentID, reqID string, shunLength time.Duration, removeDate time.Time, ) error { // Check if the IP is already shunned _, exists := d.Shuns[ip] if exists { return errors.New("ip already exists in db entry") } // Add the shun d.Shuns[ip] = Shun{ DateAdded: time.Now(), RemoveDate: removeDate, IncidentID: incidentID, ShunLength: shunLength, } // add an entry to the log d.logEntry(fmt.Sprintf("Shun added: %s, incident_id: %s, length: %d", ip, incidentID, int(shunLength.Hours())), user, reqID) // update the device in the db if err := c.updateDevice(d); err != nil { log.Error(err) return err } return nil } // RemoveShun : Remove an existing shun from the entry func (c *Client) RemoveShun(d *Device, ip, user, reqID string) error { // check if the ip exists _, exists := d.Shuns[ip] if !exists { return errors.New("ip not found in device shun list") } // delete it delete(d.Shuns, ip) // add a log entry d.logEntry(fmt.Sprintf("Shun removed: %s", ip), user, reqID) // update the db if err := c.updateDevice(d); err != nil { return err } return nil } // Close : Disconnects from the object rocket instance func (c *Client) Close() error { ctx, _ := context.WithTimeout(context.Background(), defaultTimeout) if err := c.db.Disconnect(ctx); err != nil { return err } return nil }