Skip to content

Commit

Permalink
Merge pull request #590 from threefoldtech/mock-perfection
Browse files Browse the repository at this point in the history
Mock perfection
  • Loading branch information
zaibon authored Mar 19, 2020
2 parents 3f8cb75 + 91a95b0 commit 3da7f23
Show file tree
Hide file tree
Showing 24 changed files with 448 additions and 151 deletions.
13 changes: 1 addition & 12 deletions cmds/capacityd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"github.com/threefoldtech/zos/pkg/app"
"github.com/threefoldtech/zos/pkg/capacity"
"github.com/threefoldtech/zos/pkg/environment"
"github.com/threefoldtech/zos/pkg/gedis"
"github.com/threefoldtech/zos/pkg/monitord"
"github.com/threefoldtech/zos/pkg/stubs"
"github.com/threefoldtech/zos/pkg/utils"
Expand Down Expand Up @@ -161,16 +160,6 @@ func bcdbClient() (capacity.Store, error) {
return nil, errors.Wrap(err, "failed to parse node environment")
}

// use the bcdb mock for dev and test
if env.RunningMode == environment.RunningDev {
return capacity.NewHTTPStore(env.BcdbURL), nil
}

// use gedis for production bcdb
store, err := gedis.New(env.BcdbURL, env.BcdbPassword)
if err != nil {
return nil, errors.Wrap(err, "fail to connect to BCDB")
}
return capacity.NewHTTPStore(env.BcdbURL), nil

return capacity.NewBCDBStore(store), nil
}
13 changes: 1 addition & 12 deletions cmds/identityd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"github.com/pkg/errors"
"github.com/threefoldtech/zos/pkg/app"
"github.com/threefoldtech/zos/pkg/flist"
"github.com/threefoldtech/zos/pkg/gedis"
"github.com/threefoldtech/zos/pkg/geoip"
"github.com/threefoldtech/zos/pkg/stubs"
"github.com/threefoldtech/zos/pkg/upgrade"
Expand Down Expand Up @@ -443,17 +442,7 @@ func bcdbClient() (identity.IDStore, error) {
return nil, errors.Wrap(err, "failed to parse node environment")
}

// use the bcdb mock for dev and test
if env.RunningMode == environment.RunningDev {
return identity.NewHTTPIDStore(env.BcdbURL), nil
}

// use gedis for production bcdb
store, err := gedis.New(env.BcdbURL, env.BcdbPassword)
if err != nil {
return nil, errors.Wrap(err, "fail to connect to BCDB")
}
return store, nil
return identity.NewHTTPIDStore(env.BcdbURL), nil
}

func registerNode(nodeID pkg.Identifier, farmID pkg.FarmID, version string, store identity.IDStore, loc geoip.Location) error {
Expand Down
13 changes: 1 addition & 12 deletions cmds/networkd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/threefoldtech/zos/pkg"
"github.com/threefoldtech/zos/pkg/app"
"github.com/threefoldtech/zos/pkg/environment"
"github.com/threefoldtech/zos/pkg/gedis"
"github.com/threefoldtech/zos/pkg/network"
"github.com/threefoldtech/zos/pkg/network/bootstrap"
"github.com/threefoldtech/zos/pkg/network/ndmz"
Expand Down Expand Up @@ -193,15 +192,5 @@ func bcdbClient() (network.TNoDB, error) {
return nil, errors.Wrap(err, "failed to parse node environment")
}

// use the bcdb mock for dev and test
if env.RunningMode == environment.RunningDev {
return tnodb.NewHTTPTNoDB(env.BcdbURL), nil
}

// use gedis for production bcdb
store, err := gedis.New(env.BcdbURL, env.BcdbPassword)
if err != nil {
return nil, errors.Wrap(err, "fail to connect to BCDB")
}
return store, nil
return tnodb.NewHTTPTNoDB(env.BcdbURL), nil
}
13 changes: 1 addition & 12 deletions cmds/provisiond/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/threefoldtech/zos/pkg"
"github.com/threefoldtech/zos/pkg/app"
"github.com/threefoldtech/zos/pkg/environment"
"github.com/threefoldtech/zos/pkg/gedis"

"github.com/threefoldtech/zos/pkg/stubs"
"github.com/threefoldtech/zos/pkg/utils"
Expand Down Expand Up @@ -145,15 +144,5 @@ func bcdbClient() (store, error) {
return nil, errors.Wrap(err, "failed to parse node environment")
}

// use the bcdb mock for dev and test
if env.RunningMode == environment.RunningDev {
return provision.NewHTTPStore(env.BcdbURL), nil
}

// use gedis for production bcdb
store, err := gedis.New(env.BcdbURL, env.BcdbPassword)
if err != nil {
return nil, errors.Wrap(err, "fail to connect to BCDB")
}
return store, nil
return provision.NewHTTPStore(env.BcdbURL), nil
}
4 changes: 2 additions & 2 deletions pkg/environment/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,15 @@ var (

envTest = Environment{
RunningMode: RunningTest,
BcdbURL: "tcp://explorer.testnet.grid.tf:8901",
BcdbURL: "https://explorer.testnet.grid.tf/explorer",
// ProvisionTimeout: 120,
// ProvisionInterval: 10,
}

// same as testnet for now. will be updated the day of the launch of production network
envProd = Environment{
RunningMode: RunningMain,
BcdbURL: "tcp://explorer.grid.tf:8901",
BcdbURL: "https://explorer.grid.tf/explorer",
// ProvisionTimeout: 240,
// ProvisionInterval: 20,
}
Expand Down
25 changes: 24 additions & 1 deletion pkg/provision/remote_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/rs/zerolog/log"
"github.com/threefoldtech/zos/pkg"
generated "github.com/threefoldtech/zos/pkg/gedis/types/provision"
"github.com/threefoldtech/zos/pkg/schema"
)

// HTTPStore is a reservation store
Expand Down Expand Up @@ -130,9 +131,31 @@ func (s *HTTPStore) Get(id string) (*Reservation, error) {
func (s *HTTPStore) Feedback(nodeID string, r *Result) error {
url := fmt.Sprintf("%s/reservations/workloads/%s/%s", s.baseURL, r.ID, nodeID)

var rType generated.TfgridReservationResult1CategoryEnum
switch r.Type {
case VolumeReservation:
rType = generated.TfgridReservationResult1CategoryVolume
case ContainerReservation:
rType = generated.TfgridReservationResult1CategoryContainer
case ZDBReservation:
rType = generated.TfgridReservationResult1CategoryZdb
case NetworkReservation:
rType = generated.TfgridReservationResult1CategoryNetwork
}

result := generated.TfgridReservationResult1{
Category: rType,
WorkloadID: r.ID,
DataJSON: r.Data,
Signature: r.Signature,
State: generated.TfgridReservationResult1StateEnum(r.State),
Message: r.Error,
Epoch: schema.Date{Time: r.Created},
}

buf := &bytes.Buffer{}

if err := json.NewEncoder(buf).Encode(r); err != nil {
if err := json.NewEncoder(buf).Encode(result); err != nil {
return err
}

Expand Down
1 change: 0 additions & 1 deletion pkg/schema/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,6 @@ func (e *Email) UnmarshalText(text []byte) error {
return fmt.Errorf("invalid email address: %s", v)
}

fmt.Println("setting email to:", v)
*e = Email(v)
return nil
}
Expand Down
28 changes: 28 additions & 0 deletions tools/bcdb_mock/migration/convert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from yaml import load, CLoader
import json
import sys
import os


def main(args):
if len(args) == 0:
raise Exception("required file name")
name = args[0]
input = open(name)

data = load(input, CLoader)
input.close()

output_name = "%s.json" % name
output = open(output_name, 'w')
try:
json.dump(data, output)
except Exception as e:
os.remove(output_name)
raise e
finally:
output.close()


if __name__ == '__main__':
main(sys.argv[1:])
170 changes: 170 additions & 0 deletions tools/bcdb_mock/migration/migration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package main

import (
"context"
"encoding/json"
"flag"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"

"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/threefoldtech/zos/pkg/app"
"github.com/threefoldtech/zos/tools/bcdb_mock/mw"

"go.mongodb.org/mongo-driver/mongo"

directory "github.com/threefoldtech/zos/tools/bcdb_mock/pkg/directory/types"
phonebook "github.com/threefoldtech/zos/tools/bcdb_mock/pkg/phonebook/types"
workloads "github.com/threefoldtech/zos/tools/bcdb_mock/pkg/workloads/types"
)

func foreach(root string, f func(p string, r io.Reader) error) error {
files, err := ioutil.ReadDir(root)
if err != nil {
return err
}

for _, file := range files {
if file.IsDir() {
continue
}

if filepath.Ext(file.Name()) != ".json" {
continue
}

p := filepath.Join(root, file.Name())
fd, err := os.Open(p)
if err != nil {
return err
}

if err := f(p, fd); err != nil {
fd.Close()
return err
}

fd.Close()
}

return nil
}

type Migrator func(root string, db *mongo.Database) error

func migrateFarms(root string, db *mongo.Database) error {
col := db.Collection(directory.FarmCollection)
return foreach(root, func(p string, r io.Reader) error {
var farm directory.Farm
if err := json.NewDecoder(r).Decode(&farm); err != nil {
return errors.Wrapf(err, "failed to load file '%s'", p)
}

_, err := col.InsertOne(context.TODO(), farm)
if err != nil {
log.Error().Err(err).Msgf("failed to insert farm '%s'", p)
}

return nil
})
}

func migrateNodes(root string, db *mongo.Database) error {
col := db.Collection(directory.NodeCollection)
return foreach(root, func(p string, r io.Reader) error {
var node directory.Node
if err := json.NewDecoder(r).Decode(&node); err != nil {
return errors.Wrapf(err, "failed to load file '%s'", p)
}

if err := node.Validate(); err != nil {
return errors.Wrapf(err, "file '%s'", p)
}

_, err := col.InsertOne(context.TODO(), node)
if err != nil {
log.Error().Err(err).Msgf("failed to insert node '%s'", p)
}

return nil
})
}

func migrateUsers(root string, db *mongo.Database) error {
col := db.Collection(phonebook.UserCollection)
return foreach(root, func(p string, r io.Reader) error {
var user phonebook.User
if err := json.NewDecoder(r).Decode(&user); err != nil {
return errors.Wrapf(err, "failed to load file '%s'", p)
}

_, err := col.InsertOne(context.TODO(), user)
if err != nil {
log.Error().Err(err).Msgf("failed to insert user '%s'", p)
}

return nil
})
}

func migrateReservations(root string, db *mongo.Database) error {
col := db.Collection(workloads.ReservationCollection)
return foreach(root, func(p string, r io.Reader) error {
var reservation workloads.Reservation
if err := json.NewDecoder(r).Decode(&reservation); err != nil {
return errors.Wrapf(err, "failed to load file '%s'", p)
}

_, err := col.InsertOne(context.TODO(), reservation)
if err != nil {
log.Error().Err(err).Msgf("failed to insert reservation '%s'", p)
}

return nil
})
}

func main() {
app.Initialize()

var (
root string
dbConf string
name string
)

flag.StringVar(&dbConf, "mongo", "mongodb://localhost:27017", "connection string to mongo database")
flag.StringVar(&name, "name", "explorer", "database name")
flag.StringVar(&root, "root", "", "root directory of the bcdb exported data")

flag.Parse()
if strings.EqualFold(root, "") {
log.Fatal().Msg("root option is required")
}

db, err := mw.NewDatabaseMiddleware(name, dbConf)
if err != nil {
log.Fatal().Err(err).Msg("failed to connect to database")
}

if err := directory.Setup(context.TODO(), db.Database()); err != nil {
log.Fatal().Err(err).Msg("failed to setup directory indexes")
}

types := map[string]Migrator{
"tfgrid_directory/tfgrid.directory.farm.1/yaml": migrateFarms,
"tfgrid_directory/tfgrid.directory.node.2/yaml": migrateNodes,
"phonebook/tfgrid.phonebook.user.1/yaml": migrateUsers,
"tfgrid_workloads/tfgrid.workloads.reservation.1/yaml": migrateReservations,
}

for typ, migrator := range types {
if err := migrator(filepath.Join(root, typ), db.Database()); err != nil {
log.Error().Err(err).Str("root", typ).Msg("migration failed")
}
}
}
15 changes: 15 additions & 0 deletions tools/bcdb_mock/migration/readme.me
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
## Migration
this migration tool accepts the path to a bcdb exported data directory and iterate over all structures that we need
to import in the database.

> *NOTE:* You need to convert all the data from yaml to json data. We don't support importing the yaml data. to make this easy
please use the `convert.py` util as follows

```bash
find ~/bcdb_exports/18_Mar_2020_11_48_38/ -name '*.yaml' -print -exec python convert.py {} \;
```

Then run migration like
```bash
./migration -name explorer -root ~/tmp/bcdb_exports/18_Mar_2020_11_48_38
```
2 changes: 1 addition & 1 deletion tools/bcdb_mock/models/generated/workloads/workloads.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

type TfgridWorkloadsReservation1 struct {
ID schema.ID `bson:"_id" json:"id"`
Json json.RawMessage `bson:"json" json:"json"`
Json string `bson:"json" json:"json"`
DataReservation TfgridWorkloadsReservationData1 `bson:"data_reservation" json:"data_reservation"`
CustomerTid int64 `bson:"customer_tid" json:"customer_tid"`
CustomerSignature string `bson:"customer_signature" json:"customer_signature"`
Expand Down
Loading

0 comments on commit 3da7f23

Please sign in to comment.