id
stringlengths
2
7
text
stringlengths
17
51.2k
title
stringclasses
1 value
c176900
if !debug { handlers = append( handlers, log.LvlFilterHandler( log.LvlInfo, log.StreamHandler(os.Stderr, format), ), ) } else { handlers = append(handlers, log.StreamHandler(os.Stderr, format)) } } else { handlers = append( handlers, log.LvlFilterHandler( log.LvlWarn, log.StreamHandler(os.Stderr, format), ), ) } if customHandler != nil { handlers = append(handlers, customHandler) } Log.SetHandler(log.MultiHandler(handlers...)) return Log, nil }
c176901
:= logger.Log logger.Log = newLogger return func() { logger.Log = origLog } }
c176902
return record case <-time.After(timeout): return nil } }
c176903
add context", log.Ctx{"logger": log15logger, "ctx": ctx}) return logger } return log15logger.New(ctx) }
c176904
patch := -1 if len(split) == 3 { patch, err = strconv.Atoi(split[2]) if err != nil { return nil, formatError } } return &DottedVersion{ Major: maj, Minor: min, Patch: patch, }, nil }
c176905
return nil, fmt.Errorf("Can't parse a version") } return NewDottedVersion(matches[0][1]) }
c176906
version += fmt.Sprintf(".%d", v.Patch) } return version }
c176907
!= 0 { return result } result = compareInts(v.Minor, other.Minor) if result != 0 { return result } return compareInts(v.Patch, other.Patch) }
c176908
fmt.Sprintf("Default LXD profile for project %s", project) profile.Config = map[string]string{} profile.Devices = types.Devices{} _, err := tx.ProfileCreate(profile) if err != nil { return errors.Wrap(err, "Add default profile to database") } return nil }
c176909
if req.Config["features.profiles"] == "true" { err = projectCreateDefaultProfile(tx, project.Name) if err != nil { return err } } else { // Delete the project-specific default profile. err = tx.ProfileDelete(project.Name, "default") if err != nil { return errors.Wrap(err, "Delete project default profile") } } } return nil }) if err != nil { return SmartError(err) } return EmptySyncResponse }
c176910
&& strings.Contains(project.UsedBy[0], "/profiles/default") { return true } return false } return true }
c176911
err != nil { return nil, err } // Parse it fingerprints := []string{} for _, fingerprint := range certificates { fields := strings.Split(fingerprint, "/certificates/") fingerprints = append(fingerprints, fields[len(fields)-1]) } return fingerprints, nil }
c176912
nil, "", &certificates) if err != nil { return nil, err } return certificates, nil }
c176913
raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/certificates/%s", url.QueryEscape(fingerprint)), nil, "", &certificate) if err != nil { return nil, "", err } return &certificate, etag, nil }
c176914
"/certificates", certificate, "") if err != nil { return err } return nil }
c176915
_, err := r.query("PUT", fmt.Sprintf("/certificates/%s", url.QueryEscape(fingerprint)), certificate, ETag) if err != nil { return err } return nil }
c176916
:= r.query("DELETE", fmt.Sprintf("/certificates/%s", url.QueryEscape(fingerprint)), nil, "") if err != nil { return err } return nil }
c176917
templatePath, err := getContainerTemplatePath(c, templateName) if err != nil { return SmartError(err) } if !shared.PathExists(templatePath) { return NotFound(fmt.Errorf("Path '%s' not found", templatePath)) } // Create a temporary file with the template content (since the container // storage might not be available when the file is read from FileResponse) template, err := os.Open(templatePath) if err != nil { return SmartError(err) } defer template.Close() tempfile, err := ioutil.TempFile("", "lxd_template") if err != nil { return SmartError(err) } defer tempfile.Close() _, err = io.Copy(tempfile, template) if err != nil { return InternalError(err) } files := make([]fileResponseEntry, 1) files[0].identifier = templateName files[0].path = tempfile.Name() files[0].filename = templateName return FileResponse(r, files, nil, true) }
c176918
} if r.Method == "POST" && shared.PathExists(templatePath) { return BadRequest(fmt.Errorf("Template already exists")) } // Write the new template template, err := os.OpenFile(templatePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return SmartError(err) } defer template.Close() _, err = io.Copy(template, r.Body) if err != nil { return InternalError(err) } return EmptySyncResponse }
c176919
return SmartError(err) } // Start the storage if needed ourStart, err := c.StorageStart() if err != nil { return SmartError(err) } if ourStart { defer c.StorageStop() } // Look at the request templateName := r.FormValue("path") if templateName == "" { return BadRequest(fmt.Errorf("missing path argument")) } templatePath, err := getContainerTemplatePath(c, templateName) if err != nil { return SmartError(err) } if !shared.PathExists(templatePath) { return NotFound(fmt.Errorf("Path '%s' not found", templatePath)) } // Delete the template err = os.Remove(templatePath) if err != nil { return InternalError(err) } return EmptySyncResponse }
c176920
"/") { return "", fmt.Errorf("Invalid template filename") } return filepath.Join(c.Path(), "templates", filename), nil }
c176921
+= fmt.Sprintf(" to '%v'", e.Value) } return message + fmt.Sprintf(": %s", e.Reason) }
c176922
} return fmt.Sprintf("%s (and %d more errors)", l[0], len(l)-1) }
c176923
*l = append(*l, &Error{name, value, reason}) }
c176924
database schema") } err = node.SchemaDotGo() if err != nil { return errors.Wrap(err, "Update node database schema") } return nil }
c176925
err := doProfileUpdateContainer(d, name, old, nodeName, args) if err != nil { failures[args.Name] = err } } if len(failures) != 0 { msg := "The following containers failed to update (profile change still saved):\n" for cname, err := range failures { msg += fmt.Sprintf(" - %s: %s\n", cname, err) } return fmt.Errorf("%s", msg) } return nil }
c176926
} } c := containerLXCInstantiate(d.State(), args) c.expandConfig(profiles) c.expandDevices(profiles) return c.Update(db.ContainerArgs{ Architecture: c.Architecture(), Config: c.LocalConfig(), Description: c.Description(), Devices: c.LocalDevices(), Ephemeral: c.IsEphemeral(), Profiles: c.Profiles(), Project: c.Project(), }, true) }
c176927
container, err := tx.ContainerGet(ctProject, ctName) if err != nil { return err } containers = append(containers, db.ContainerToArgs(container)) } } return nil }) if err != nil { return nil, errors.Wrapf(err, "Failed to fetch containers") } return containers, nil }
c176928
:= []string{} for _, url := range urls { fields := strings.Split(url, "/networks/") names = append(names, fields[len(fields)-1]) } return names, nil }
c176929
_, err := r.queryStruct("GET", "/networks?recursion=1", nil, "", &networks) if err != nil { return nil, err } return networks, nil }
c176930
etag, err := r.queryStruct("GET", fmt.Sprintf("/networks/%s", url.QueryEscape(name)), nil, "", &network) if err != nil { return nil, "", err } return &network, etag, nil }
c176931
_, err := r.queryStruct("GET", fmt.Sprintf("/networks/%s/leases", url.QueryEscape(name)), nil, "", &leases) if err != nil { return nil, err } return leases, nil }
c176932
_, err := r.queryStruct("GET", fmt.Sprintf("/networks/%s/state", url.QueryEscape(name)), nil, "", &state) if err != nil { return nil, err } return &state, nil }
c176933
_, err := r.query("POST", "/networks", network, "") if err != nil { return err } return nil }
c176934
_, err := r.query("PUT", fmt.Sprintf("/networks/%s", url.QueryEscape(name)), network, ETag) if err != nil { return err } return nil }
c176935
err := r.query("POST", fmt.Sprintf("/networks/%s", url.QueryEscape(name)), network, "") if err != nil { return err } return nil }
c176936
// Create the cluster db. This won't immediately establish any network // connection, that will happen only when a db transaction is started // (see the database/sql connection pooling code for more details). if name == "" { name = "db.bin" } db, err := sql.Open(driverName, name) if err != nil { return nil, fmt.Errorf("cannot open cluster database: %v", err) } return db, nil }
c176937
range query { params.Add(key, value) } u.RawQuery = params.Encode() return u.String(), nil }
c176938
false } return (stat.Mode() & os.ModeSocket) == os.ModeSocket }
c176939
parent as snap-confine alters our own cwd on launch ppid := os.Getppid() if ppid < 1 { return path } pwd, err := os.Readlink(fmt.Sprintf("/proc/%d/cwd", ppid)) if err != nil { return path } path = filepath.Clean(strings.Join([]string{pwd, path}, string(os.PathSeparator))) } // Check if the path is already snap-aware for _, prefix := range []string{"/dev", "/snap", "/var/snap", "/var/lib/snapd"} { if path == prefix || strings.HasPrefix(path, fmt.Sprintf("%s/", prefix)) { return path } } return fmt.Sprintf("/var/lib/snapd/hostfs%s", path) }
c176940
if err != nil { return err } os.Remove(oldPath) return nil }
c176941
nil { return errors.Wrapf(err, "failed to create destination directory %s", dest) } // Copy all files. entries, err := ioutil.ReadDir(source) if err != nil { return errors.Wrapf(err, "failed to read source directory %s", source) } for _, entry := range entries { sourcePath := filepath.Join(source, entry.Name()) destPath := filepath.Join(dest, entry.Name()) if entry.IsDir() { err := DirCopy(sourcePath, destPath) if err != nil { return errors.Wrapf(err, "failed to copy sub-directory from %s to %s", sourcePath, destPath) } } else { err := FileCopy(sourcePath, destPath) if err != nil { return errors.Wrapf(err, "failed to copy file from %s to %s", sourcePath, destPath) } } } return nil }
c176942
for _, k := range keys { if _, ok := m[k]; ok { return true } } return false }
c176943
return []byte{}, err } f.Write(inContent) f.Close() path = fmt.Sprintf("%s.yaml", f.Name()) os.Rename(f.Name(), path) defer os.Remove(path) } else { path = inPath } cmdParts := strings.Fields(editor) cmd := exec.Command(cmdParts[0], append(cmdParts[1:], path)...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { return []byte{}, err } content, err := ioutil.ReadFile(path) if err != nil { return []byte{}, err } return content, nil }
c176944
if err != nil { return "", err } defer f.Close() _, err = f.WriteString(content) return f.Name(), err }
c176945
// Looks like we're nesting templates so run pongo again if strings.Contains(ret, "{{") || strings.Contains(ret, "{%") { return RenderTemplate(ret, ctx) } return ret, err }
c176946
error if first && every.skipFirst { err = ErrSkip } first = false return interval, err } }
c176947
lxdStorageMapLock.Lock() if waitChannel, ok := lxdStorageOngoingOperationMap[poolMountLockID]; ok { close(waitChannel) delete(lxdStorageOngoingOperationMap, poolMountLockID) } lxdStorageMapLock.Unlock() } defer removeLockFromMap() if filepath.IsAbs(source) && !shared.IsBlockdevPath(source) { // Try to prepare new loop device. loopF, loopErr := prepareLoopDev(source, 0) if loopErr != nil { return false, loopErr } // Make sure that LO_FLAGS_AUTOCLEAR is unset. loopErr = unsetAutoclearOnLoopDev(int(loopF.Fd())) if loopErr != nil { return false, loopErr } s.loopInfo = loopF } return true, nil }
c176948
dump += tableDump } // Sequences (unless the schemaOnly flag is true) if !schemaOnly { tableDump, err = dumpTable(tx, "sqlite_sequence", "DELETE FROM sqlite_sequence;") if err != nil { return "", errors.Wrapf(err, "failed to dump table sqlite_sequence") } dump += tableDump } // Commit dump += "COMMIT;\n" return dump, nil }
c176949
int64: values[j] = strconv.FormatInt(v, 10) case string: values[j] = fmt.Sprintf("'%s'", v) case []byte: values[j] = fmt.Sprintf("'%s'", string(v)) case time.Time: values[j] = strconv.FormatInt(v.Unix(), 10) default: if v != nil { return "", fmt.Errorf("bad type in column %s of row %d", columns[j], i) } values[j] = "NULL" } } statement := fmt.Sprintf("INSERT INTO %s VALUES(%s);", table, strings.Join(values, ",")) statements = append(statements, statement) } return strings.Join(statements, "\n") + "\n", nil }
c176950
return projectHasProfiles(c.tx, name) }
c176951
{ return nil, errors.Wrap(err, "Fetch project names") } return names, nil }
c176952
result := map[int64]string{} for i := 0; rows.Next(); i++ { var id int64 var name string err := rows.Scan(&id, &name) if err != nil { return nil, err } result[id] = name } err = rows.Err() if err != nil { return nil, err } return result, nil }
c176953
if err != nil { return false, errors.Wrap(err, "fetch project") } enabled := project.Config["features.images"] == "true" return enabled, nil }
c176954
err = c.tx.Exec(` DELETE FROM projects_config WHERE projects_config.project_id = ? `, id) if err != nil { return errors.Wrap(err, "Delete project config") } // Insert new config. stmt = c.stmt(projectCreateConfigRef) for key, value := range object.Config { _, err := stmt.Exec(id, key, value) if err != nil { return errors.Wrap(err, "Insert config for project") } } return nil }
c176955
the required \"clustering\" API extension") } cluster := &api.Cluster{} etag, err := r.queryStruct("GET", "/cluster", nil, "", &cluster) if err != nil { return nil, "", err } return cluster, etag, nil }
c176956
return nil, fmt.Errorf("The server is missing the required \"clustering_join\" API extension") } } op, _, err := r.queryOperation("PUT", "/cluster", cluster, "") if err != nil { return nil, err } return op, nil }
c176957
r.queryStruct("GET", "/cluster/members", nil, "", &urls) if err != nil { return nil, err } return urls, nil }
c176958
required \"clustering\" API extension") } members := []api.ClusterMember{} _, err := r.queryStruct("GET", "/cluster/members?recursion=1", nil, "", &members) if err != nil { return nil, err } return members, nil }
c176959
fmt.Sprintf("/cluster/members/%s", name), nil, "", &member) if err != nil { return nil, "", err } return &member, etag, nil }
c176960
is missing the required \"clustering\" API extension") } _, _, err := r.query("POST", fmt.Sprintf("/cluster/members/%s", name), member, "") if err != nil { return err } return nil }
c176961
e.r.eventListeners[len(e.r.eventListeners)-1] = nil e.r.eventListeners = e.r.eventListeners[:len(e.r.eventListeners)-1] break } } // Turn off the handler e.err = nil e.disconnected = true close(e.chActive) }
c176962
extensions1 == extensions2 { return 0, nil } if schema1 >= schema2 && extensions1 >= extensions2 { return 1, nil } if schema1 <= schema2 && extensions1 <= extensions2 { return 2, nil } return -1, fmt.Errorf("nodes have inconsistent versions") }
c176963
!shared.PathExists(certf) || !shared.PathExists(keyf) { return false } return true }
c176964
keyf := c.ConfigPath("client.key") return shared.FindOrGenCert(certf, keyf, true) }
c176965
_, err := shared.RunCommand("modprobe", module) return err }
c176966
file, err := parser.ParseFile(fset, path, nil, parser.ParseComments) if err != nil { return nil, fmt.Errorf("Parse Go source file %q", path) } files[path] = file } // Ignore errors because they are typically about unresolved symbols. pkg, _ := ast.NewPackage(fset, files, nil, nil) return pkg, nil }
c176967
nil { return "" } return listener.Addr().String() }
c176968
nil { return nil, fmt.Errorf("Cannot listen on http socket: %v", err) } return &listener, nil } // If setting a new address, setup the listener if address != "" { listener, err := getListener(address) if err != nil { // Attempt to revert to the previous address listener, err1 := getListener(oldAddress) if err1 == nil { e.listeners[pprof] = *listener e.serveHTTP(pprof) } return err } e.listeners[pprof] = *listener e.serveHTTP(pprof) } return nil }
c176969
entity: entity, kind: kind, config: config, packages: packages, } return method, nil }
c176970
return m.get(buf) case "ID": return m.id(buf) case "Exists": return m.exists(buf) case "Create": return m.create(buf) case "Rename": return m.rename(buf) case "Update": return m.update(buf) case "Delete": return m.delete(buf) default: return fmt.Errorf("Unknown method kind '%s'", m.kind) } }
c176971
subIndex := %s{}", subIndexTyp) buf.L(" %s%s = subIndex", objectsVar, needle) buf.L(" }") buf.N() } needle += fmt.Sprintf("[objects[i].%s]", nk[len(nk)-1].Name) buf.L(" value := %s%s", objectsVar, needle) buf.L(" if value == nil {") buf.L(" value = %s{}", field.Type.Name) buf.L(" }") buf.L(" objects[i].%s = value", field.Name) buf.L("}") buf.N() return nil }
c176972
{ case 0: return -1, ErrNoSuchObject case 1: return int64(ids[0]), nil default: return -1, fmt.Errorf("more than one pool has the given name") } }
c176973
} stmt, err := c.tx.Prepare("SELECT id, name FROM storage_pools WHERE NOT state=?") if err != nil { return nil, err } defer stmt.Close() err = query.SelectObjects(stmt, dest, storagePoolPending) if err != nil { return nil, err } ids := map[string]int64{} for _, pool := range pools { ids[pool.name] = pool.id } return ids, nil }
c176974
if err != nil { return errors.Wrap(err, "failed to add storage pools node entry") } return nil }
c176975
node's ceph volume IDs") } otherVolumeIDs, err := query.SelectIntegers(c.tx, stmt, poolID, otherNodeID) if err != nil { return errors.Wrap(err, "failed to get other node's ceph volume IDs") } if len(volumeIDs) != len(otherVolumeIDs) { // Sanity check return fmt.Errorf("not all ceph volumes were copied") } for i, otherVolumeID := range otherVolumeIDs { config, err := query.SelectConfig( c.tx, "storage_volumes_config", "storage_volume_id=?", otherVolumeID) if err != nil { return errors.Wrap(err, "failed to get storage volume config") } for key, value := range config { _, err := c.tx.Exec(` INSERT INTO storage_volumes_config(storage_volume_id, key, value) VALUES(?, ?, ?) `, volumeIDs[i], key, value) if err != nil { return errors.Wrap(err, "failed to copy volume config") } } } return nil }
c176976
return storagePoolConfigAdd(c.tx, poolID, nodeID, config) }
c176977
c.NodeByName(node) if err != nil { return err } // Check that no storage_pool entry of this node and pool exists yet. count, err := query.Count( c.tx, "storage_pools_nodes", "storage_pool_id=? AND node_id=?", poolID, nodeInfo.ID) if err != nil { return err } if count != 0 { return ErrAlreadyDefined } // Insert the node-specific configuration. columns := []string{"storage_pool_id", "node_id"} values := []interface{}{poolID, nodeInfo.ID} _, err = query.UpsertObject(c.tx, "storage_pools_nodes", columns, values) if err != nil { return err } err = c.StoragePoolConfigAdd(poolID, nodeInfo.ID, conf) if err != nil { return err } return nil }
c176978
c.storagePoolState(name, storagePoolCreated) }
c176979
c.storagePoolState(name, storagePoolErrored) }
c176980
fmt.Errorf("Pool not defined on nodes: %s", strings.Join(missing, ", ")) } configs := map[string]map[string]string{} for _, node := range nodes { config, err := query.SelectConfig( c.tx, "storage_pools_config", "storage_pool_id=? AND node_id=?", poolID, node.ID) if err != nil { return nil, err } configs[node.Name] = config } return configs, nil }
c176981
result, err := queryScan(c.db, query, inargs, outargs) if err != nil { return []string{}, err } if len(result) == 0 { return []string{}, ErrNoSuchObject } drivers := []string{} for _, driver := range result { drivers = append(drivers, driver[0].(string)) } return drivers, nil }
c176982
:= dbQueryRowScan(c.db, query, inargs, outargs) if err != nil { if err == sql.ErrNoRows { return -1, ErrNoSuchObject } } return poolID, nil }
c176983
return -1, nil, ErrNoSuchObject } return -1, nil, err } config, err := c.StoragePoolConfigGet(poolID) if err != nil { return -1, nil, err } storagePool := api.StoragePool{ Name: poolName, Driver: poolDriver, } storagePool.Description = description.String storagePool.Config = config switch state { case storagePoolPending: storagePool.Status = "Pending" case storagePoolCreated: storagePool.Status = "Created" default: storagePool.Status = "Unknown" } nodes, err := c.storagePoolNodes(poolID) if err != nil { return -1, nil, err } storagePool.Locations = nodes return poolID, &storagePool, nil }
c176984
var err error nodes, err = query.SelectStrings(tx.tx, stmt, poolID) return err }) if err != nil { return nil, err } return nodes, nil }
c176985
if err != nil { return nil, err } config := map[string]string{} for _, r := range results { key = r[0].(string) value = r[1].(string) config[key] = value } return config, nil }
c176986
} // Insert a node-specific entry pointing to ourselves. columns := []string{"storage_pool_id", "node_id"} values := []interface{}{id, c.nodeID} _, err = query.UpsertObject(tx.tx, "storage_pools_nodes", columns, values) if err != nil { return err } err = storagePoolConfigAdd(tx.tx, id, c.nodeID, poolConfig) if err != nil { return err } return nil }) if err != nil { id = -1 } return id, nil }
c176987
var nodeIDValue interface{} if !shared.StringInSlice(k, StoragePoolNodeConfigKeys) { nodeIDValue = nil } else { nodeIDValue = nodeID } _, err = stmt.Exec(poolID, nodeIDValue, k, v) if err != nil { return err } } return nil }
c176988
err = StoragePoolUpdateDescription(tx.tx, poolID, description) if err != nil { return err } err = StoragePoolConfigClear(tx.tx, poolID, c.nodeID) if err != nil { return err } err = storagePoolConfigAdd(tx.tx, poolID, c.nodeID, poolConfig) if err != nil { return err } return nil }) return err }
c176989
storage_pools_config WHERE storage_pool_id=? AND (node_id=? OR node_id IS NULL)", poolID, nodeID) if err != nil { return err } return nil }
c176990
"DELETE FROM storage_pools WHERE id=?", poolID) if err != nil { return nil, err } return pool, nil }
c176991
err != nil { return []string{}, err } var out []string for _, r := range result { out = append(out, r[0].(string)) } return out, nil }
c176992
WHERE (projects.name=? OR storage_volumes.type=?) AND storage_pool_id=? `, project, StoragePoolVolumeTypeCustom, poolID) return err }) if err != nil { return nil, err } volumes := []*api.StorageVolume{} for _, nodeID := range nodeIDs { nodeVolumes, err := c.storagePoolVolumesGet(project, poolID, int64(nodeID), volumeTypes) if err != nil { return nil, err } volumes = append(volumes, nodeVolumes...) } return volumes, nil }
c176993
return c.storagePoolVolumesGet("default", poolID, c.nodeID, volumeTypes) }
c176994
{ _, volume, err := c.StoragePoolVolumeGetType(project, volumeName, volumeType, poolID, nodeID) if err != nil { return nil, errors.Wrap(err, "failed to fetch volume type") } result = append(result, volume) } } if len(result) == 0 { return result, ErrNoSuchObject } return result, nil }
c176995
:= []interface{}{poolName} result, err := queryScan(c.db, query, inargs, outargs) if err != nil { return []string{}, err } response := []string{} for _, r := range result { response = append(response, r[0].(string)) } return response, nil }
c176996
outfmt := []interface{}{volumeName} dbResults, err := queryScan(c.db, query, inargs, outfmt) if err != nil { return result, err } for _, r := range dbResults { result = append(result, r[0].(string)) } return result, nil }
c176997
return c.StoragePoolVolumesGetType("default", volumeType, poolID, c.nodeID) }
c176998
err := c.StorageVolumeNodeGet(volumeID) if err != nil { return -1, nil, err } volumeConfig, err := c.StorageVolumeConfigGet(volumeID) if err != nil { return -1, nil, err } volumeDescription, err := c.StorageVolumeDescriptionGet(volumeID) if err != nil { return -1, nil, err } volumeTypeName, err := StoragePoolVolumeTypeToName(volumeType) if err != nil { return -1, nil, err } storageVolume := api.StorageVolume{ Type: volumeTypeName, } storageVolume.Name = volumeName storageVolume.Description = volumeDescription storageVolume.Config = volumeConfig storageVolume.Location = volumeNode return volumeID, &storageVolume, nil }
c176999
return c.StoragePoolNodeVolumeGetTypeByProject("default", volumeName, volumeType, poolID) }