// InitDbLogs sets up the indexes for the logs collection. It should
// be called as state is opened. It is idempotent.
9741
func InitDbLogs(session *mgo.Session, modelUUID string) error {
	logsColl := session.DB(logsDB).C(logCollectionName(modelUUID))
	for _, key := range logIndexes {
		err := logsColl.EnsureIndex(mgo.Index{Key: key})
		if err != nil {
			return errors.Annotate(err, "cannot create index for logs collection")
		}
	}
	return nil
}
570721
func (f *Filter) indexedLogs(ctx context.Context, end uint64) ([]*types.Log, error) {
	// Create a matcher session and request servicing from the backend
	matches := make(chan uint64, 64)

	session, err := f.matcher.Start(ctx, uint64(f.begin), end, matches)
	if err != nil {
		return nil, err
	}
	defer session.Close()

	f.backend.ServiceFilter(ctx, session)

	// Iterate over the matches until exhausted or context closed
	var logs []*types.Log

	for {
		select {
		case number, ok := <-matches:
			// Abort if all matches have been fulfilled
			if !ok {
				err := session.Error()
				if err == nil {
					f.begin = int64(end) + 1
				}
				return logs, err
			}
			f.begin = int64(number) + 1

			// Retrieve the suggested block and pull any truly matching logs
			header, err := f.backend.HeaderByNumber(ctx, rpc.BlockNumber(number))
			if header == nil || err != nil {
				return logs, err
			}
			found, err := f.checkMatches(ctx, header)
			if err != nil {
				return logs, err
			}
			logs = append(logs, found...)

		case <-ctx.Done():
			return logs, ctx.Err()
		}
	}
}
809732
func (db *DB) init() error {
	// Set the page size to the OS page size.
	db.pageSize = os.Getpagesize()

	// Create two meta pages on a buffer.
	buf := make([]byte, db.pageSize*4)
	for i := 0; i < 2; i++ {
		p := db.pageInBuffer(buf[:], pgid(i))
		p.id = pgid(i)
		p.flags = metaPageFlag

		// Initialize the meta page.
		m := p.meta()
		m.magic = magic
		m.version = version
		m.pageSize = uint32(db.pageSize)
		m.freelist = 2
		m.root = bucket{root: 3}
		m.pgid = 4
		m.txid = txid(i)
		m.checksum = m.sum64()
	}

	// Write an empty freelist at page 3.
	p := db.pageInBuffer(buf[:], pgid(2))
	p.id = pgid(2)
	p.flags = freelistPageFlag
	p.count = 0

	// Write an empty leaf page at page 4.
	p = db.pageInBuffer(buf[:], pgid(3))
	p.id = pgid(3)
	p.flags = leafPageFlag
	p.count = 0

	// Write the buffer to our data file.
	if _, err := db.ops.writeAt(buf, 0); err != nil {
		return err
	}
	if err := fdatasync(db); err != nil {
		return err
	}

	return nil
}
868269
func (tqsc *Controller) InitDBConfig(target querypb.Target, dbcfgs *dbconfigs.DBConfigs) error {
	tqsc.mu.Lock()
	defer tqsc.mu.Unlock()

	tqsc.CurrentTarget = target
	return nil
}
346412
func initDB(ldb *leveldb.DB) error {
	// The starting block file write cursor location is file num 0, offset
	// 0.
	batch := new(leveldb.Batch)
	batch.Put(bucketizedKey(metadataBucketID, writeLocKeyName),
		serializeWriteRow(0, 0))

	// Create block index bucket and set the current bucket id.
	//
	// NOTE: Since buckets are virtualized through the use of prefixes,
	// there is no need to store the bucket index data for the metadata
	// bucket in the database.  However, the first bucket ID to use does
	// need to account for it to ensure there are no key collisions.
	batch.Put(bucketIndexKey(metadataBucketID, blockIdxBucketName),
		blockIdxBucketID[:])
	batch.Put(curBucketIDKeyName, blockIdxBucketID[:])

	// Write everything as a single batch.
	if err := ldb.Write(batch, nil); err != nil {
		str := fmt.Sprintf("failed to initialize metadata database: %v",
			err)
		return convertErr(str, err)
	}

	return nil
}
1223566
func (m *MDBStore) initialize() error {
	// Allow up to 2 sub-dbs
	if err := m.env.SetMaxDBs(mdb.DBI(2)); err != nil {
		return err
	}

	// Increase the maximum map size
	if err := m.env.SetMapSize(m.maxSize); err != nil {
		return err
	}

	// Open the DB
	if err := m.env.Open(m.path, mdb.NOTLS, 0755); err != nil {
		return err
	}

	// Create all the tables
	tx, _, err := m.startTxn(false, dbLogs, dbConf)
	if err != nil {
		tx.Abort()
		return err
	}
	return tx.Commit()
}
1168324
func (db *Database) printLog(v interface{}) {
	if db.logger != nil {
		db.logger.Print(v)
	}
}
1159731
func (f *Filter) unindexedLogs(ctx context.Context, end uint64) ([]*types.Log, error) {
	var logs []*types.Log

	for ; f.begin <= int64(end); f.begin++ {
		header, err := f.backend.HeaderByNumber(ctx, rpc.BlockNumber(f.begin))
		if header == nil || err != nil {
			return logs, err
		}
		found, err := f.blockLogs(ctx, header)
		if err != nil {
			return logs, err
		}
		logs = append(logs, found...)
	}
	return logs, nil
}
1010917
func initFilterLog(c *CompositeMultiHandler, basePath string, config *config.Context) {

	if config != nil {
		extraLogFlag := config.BoolDefault(SPECIAL_USE_FLAG, false)

		for _, logFilter := range logFilterList {
			// Init for all filters
			for _, name := range []string{"all", "debug", "info", "warn", "error", "crit",
				"trace", // TODO trace is deprecated
			} {
				optionList := config.Options(logFilter.LogPrefix + name + logFilter.LogSuffix)
				for _, option := range optionList {
					splitOptions := strings.Split(option, ".")
					keyMap := map[string]interface{}{}
					for x := 3; x < len(splitOptions); x += 2 {
						keyMap[splitOptions[x]] = splitOptions[x+1]
					}
					phandler := logFilter.parentHandler(keyMap)
					if extraLogFlag {
						log.Printf("Adding key map handler %s %s output %s", option, name, config.StringDefault(option, ""))
						fmt.Printf("Adding key map handler %s %s output %s matching %#v\n", option, name, config.StringDefault(option, ""), keyMap)
					}

					if name == "all" {
						initHandlerFor(c, config.StringDefault(option, ""), basePath, NewLogOptions(config, false, phandler))
					} else {
						initHandlerFor(c, config.StringDefault(option, ""), basePath, NewLogOptions(config, false, phandler, toLevel[name]))
					}
				}
			}
		}
	}
}
976428
func (c *ServicedCli) initLog() {
	c.app.Commands = append(c.app.Commands, cli.Command{
		Name:        "log",
		Usage:       "Administers logs",
		Description: "",
		Subcommands: []cli.Command{
			{
				Name:        "export",
				Usage:       "Exports application log data",
				Description: "serviced log export",
				// TODO: BashComplete: c.printLogExportCompletion,
				Action: c.cmdExportLogs,
				Flags: []cli.Flag{
					cli.StringFlag{
						Name:  "from",
						Value: "",
						Usage: "yyyy.mm.dd",
					},
					cli.StringFlag{
						Name:  "to",
						Value: "",
						Usage: "yyyy.mm.dd",
					},
					cli.StringSliceFlag{
						Name:  "service",
						Value: &cli.StringSlice{},
						Usage: "service ID or name (includes all child services)",
					},
					cli.StringSliceFlag{
						Name:  "file",
						Value: &cli.StringSlice{},
						Usage: "the application log filename",
					},
					cli.StringFlag{
						Name:  "out",
						Value: "",
						Usage: "path to output file",
					},
					cli.BoolFlag{
						Name:  "debug, d",
						Usage: "Show additional diagnostic messages",
					},
					cli.StringFlag{
						Name:  "group-by",
						Value: "container",
						Usage: "Group results either by container, service or day",
					},
					cli.BoolFlag{
						Name:  "no-children, n",
						Usage: "Do not export child services",
					},
				},
			},
		},
	})
}
1029001
func initLogsSession(st ModelSessioner) (*mgo.Session, *mgo.Collection) {
	session, db := initLogsSessionDB(st)
	return session, db.C(logCollectionName(st.ModelUUID()))
}
1325349
func (s *Storage) Init() error {
	dbPath = s.config.Stat.LevelDB.Path
	return nil
}
52235
func addLogs(target map[string]string, logs []opentracing.LogRecord) {
	for i, l := range logs {
		buf := bytes.NewBufferString(l.Timestamp.String())
		for j, f := range l.Fields {
			buf.WriteString(f.Key())
			buf.WriteString("=")
			buf.WriteString(fmt.Sprint(f.Value()))
			if j != len(l.Fields)+1 {
				buf.WriteString(" ")
			}
		}
		target[fmt.Sprintf("event_%d", i)] = buf.String()
	}
}
164582
func InitDB(path string, params *chaincfg.Params) (*PublicRecord, error) {
	path = filepath.Clean(path)
	// Check if the file exists and remove it if it does.
	if _, err := os.Stat(path); err == nil {
		if err := os.Remove(path); err != nil {
			return nil, err
		}
	}

	conn, err := sql.Open("sqlite3", path)
	if err != nil {
		return nil, err
	}

	// Execute the Create Table sql
	_, err = conn.Exec(createSql())
	if err != nil {
		return nil, err
	}
	conn.Close()

	db, err := createPubRec(path)
	if err != nil {
		return nil, err
	}

	// Prepare the DB to do one insert (for the pegBlk)
	if err := prepareInserts(db); err != nil {
		return nil, err
	}

	err = db.InsertGenesisBlk(params.Net)
	if err != nil {
		return nil, err
	}
	return prepareDB(db)
}
798223
func InitLogger(handle io.Writer, prefix string) *log.Logger {
	return log.New(handle, strings.Join([]string{prefix, ": "}, ""), log.Ldate|log.Ltime|log.Lshortfile)
}
563728
func initLogLevels(c *CompositeMultiHandler, basePath string, config *config.Context) {
	for _, name := range []string{"debug", "info", "warn", "error", "crit",
		"trace", // TODO trace is deprecated
	} {
		if config != nil {
			extraLogFlag := config.BoolDefault(SPECIAL_USE_FLAG, false)
			output, found := config.String("log." + name + ".output")
			if found {
				if extraLogFlag {
					log.Printf("Adding standard handler %s output %s", name, output)
				}
				initHandlerFor(c, output, basePath, NewLogOptions(config, true, nil, toLevel[name]))
			}
			// Gets the list of options with said prefix
		} else {
			initHandlerFor(c, "stderr", basePath, NewLogOptions(config, true, nil, toLevel[name]))
		}
	}
}
491533
func (w *collectionWatcher) initial() ([]string, error) {
	var ids []string
	var doc struct {
		DocId string `bson:"_id"`
	}
	coll, closer := w.db.GetCollection(w.col)
	defer closer()
	iter := coll.Find(nil).Iter()
	for iter.Next(&doc) {
		if w.filter == nil || w.filter(doc.DocId) {
			id := doc.DocId
			if !w.colWCfg.global {
				id = w.backend.localID(id)
			}
			if w.idconv != nil {
				id = w.idconv(id)
			}
			ids = append(ids, id)
		}
	}
	return ids, iter.Close()
}